Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 关联数组排序值_Sorting_Lua_Lua Table - Fatal编程技术网

Sorting 关联数组排序值

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'])

我有下面的代码,它应该根据“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)