Sorting 关联数组排序值
我有下面的代码,它应该根据“pos”值返回一个排序数组Sorting 关联数组排序值,sorting,lua,lua-table,Sorting,Lua,Lua Table,我有下面的代码,它应该根据“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'])
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
预期(按“位置”字母顺序排列):
A,,
C
D
有什么问题吗?来自
表的文档。排序(表[,comp])
在:
[comp]此order函数接收两个参数,如果
在排序数组中,第一个参数应排在第一位
因此,将函数更改为:
function comp(w1,w2)
return w1['pos'] < w2['pos']
end
table.sort(tables, function(w1, w2) return w1.pos < w2.pos end)