返回Lua中的已排序列表&s索引 [英] Returning A Sorted List's Index in Lua

查看:25
本文介绍了返回Lua中的已排序列表&s索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用索引号访问对象属性

object = {}
object.y = {60,20,40}
object.g = {box1,box2,box3} -- graphic
object.c = {false,false,false} -- collision
-- object.y[2] is 20 and its graphic is box2
-- sorted by y location, index should be, object.sort = {2,3,1}

我知道table.sort对列表进行排序,但我如何对返回索引的y列表进行排序,以便根据y位置在前面绘制每个对象。

也许可以编辑快速排序功能,我不明白。 http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Lua

https://github.com/mirven/lua_snippets/blob/master/lua/quicksort.lua

这可能吗?

推荐答案

这应该可以工作:

local temp = {}
local values = object.y
-- filling temp with all indexes
for i=1,#values do
    temp[i] = i
end
-- sorting the indexes, using object.y as comparison
table.sort(temp,function(a,b)
    return values[a] < values[b]
end)
-- sorting is done here, have fun with it
object.sort = temp

将此代码与您的代码结合使用时,Temp将为{2,3,1}。

这篇关于返回Lua中的已排序列表&amp;s索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆