关联数组排序值

我有以下代码,应该根据其'pos'值返回已排序的数组。

local tables = {}

table.insert(tables,{ ['pos']=2, ['name'] = 'C' })
table.insert(tables, {['pos']=1, ['name'] = 'A' })
table.insert(tables,{ ['pos']=30, ['name'] = 'D'} )

function comp(w1,w2)
    if tonumber(w1['pos']) > tonumber(w2['pos']) then
        return true
    end
end

table.sort(tables, comp)

for key,val in pairs(tables) do
    print(val['name'])
end

结果是:

D C A

预期按其“pos”的字母顺序排序:

A, C, D

哪里出了问题?

点赞
用户2726734
用户2726734

PILtable.sort(table [, comp])文档中可以得知:

[comp] 此排序函数接收两个参数并返回true,如果第一个参数在排序后的数组中应该排在第一个。

因此更改函数为:

function comp(w1, w2)
    return w1['pos'] < w2['pos']
end

注意:tonumberif在此处都是不必要的。

正如@lhf所指出的那样,这样做更简单:

table.sort(tables, function(w1, w2) return w1.pos < w2.pos end)
2015-02-18 17:28:21