Lua中如何返回已排序列表的索引

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

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
-- 按照y位置排序,索引应该是object.sort = {2,3,1}

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

也许可以编辑quicksort函数,但我不理解它。 http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Lua

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

这可能吗?

点赞
用户1190388
用户1190388

不要按照当前的方式存储数据。使用以下方式:

object = {
  {
    y = 60,
    g = box1,
    c = false,
  },
  {
    y = 20,
    g = box2,
    c = false,
  },
  {
    y = 40,
    g = box3,
    c = false,
  },
}

然后在 table.sort 中使用以下回调函数:

function CustomSort(L, R)
  return L.y > R.y
end

如下所示:

table.sort(object, CustomSort)
2016-02-10 09:15:46
用户5352026
用户5352026

这应该可行:

local temp = {}
local values = object.y
-- 用所有索引填充temp
for i=1,#values do
    temp[i] = i
end
-- 使用object.y作为比较方法对索引进行排序
table.sort(temp,function(a,b)
    return values[a] < values[b]
end)
-- 排序完成,愉快的使用它吧
object.sort = temp

当将这个代码与您的代码结合使用时,temp将为{2,3,1}。

2016-02-10 11:43:26
用户5893999
用户5893999

这是我收到的答案的最终版本。我的问题已经解决了。

使用sortIndex(object)可以在object.sort中获取排序列表。对象移动后更新排序。

box1 = love.graphics.newImage("tile1.png")
box2 = love.graphics.newImage("tile2.png")
box3 = love.graphics.newImage("tile3.png")
hero = love.graphics.newImage("hero.png")
object = {
    {   x = 200,    y =  50,    g = box1 },
    {   x =  50,    y = 100,    g = box2 },
    {   x = 150,    y = 200,    g = box3 },
    {   x =   0,    y =   0,    g = hero }
}
function sortIndex(item)
--  Sort id, using item values
    local function sortY(a,b)
        return item[a].y < item[b].y
    end
    --------------------------------
    local i
    local id = {}       -- id list
    for i = 1, #item do -- Fill id list
        id[i] = i
    end
--  print( unpack(id) ) -- Check before
    table.sort(id,sortY)-- Sort list
--  print( unpack(id) ) -- Check after
    item.sort = id      -- List added to object.sort
end

sortIndex(object) -- print( unpack(object.sort) ) -- Check sorted id's

function drawObject()
    local i,v, g,x,y
    for i = 1, #object do
        v = object.sort[i] -- Draw in order
        x = object[v].x
        y = object[v].y
        g = object[v].g
        love.graphics.draw(g,x,y)
    end
end
2016-02-11 07:08:53