sorting a table in descending order in Lua

99封情书 提交于 2019-12-08 04:39:01

问题


I can not get it work:

tbl = {
    [1] = { ['etc2'] = 14477 },
    [2] = { ['etc1'] = 1337 },
    [3] = { ['etc3'] = 1336 },
    [4] = { ['etc4'] = 1335 }
}

for i = 1, #tbl do
    table.sort(tbl, function(a, b) return a[i] > b[i] end)
    print(tbl[i] .. '==' .. #tbl)
end

Getting this error: attempt to compare two nil values

This is a follow-on to table value sorting in lua


回答1:


How about this?

tbl = {
    { 'etc3', 1336 },
    { 'etc2', 14477 },
    { 'etc4', 1335 },
    { 'etc1', 1337 },
}

table.sort(tbl, function(a, b) return a[2] > b[2] end)

for k,v in ipairs(tbl) do
    print(v[1], ' == ', v[2])
end

Organizing the data that way made it easier to sort, and note that I only call table.sort once, not once per element of the table. And I sort based on the second value in the subtables, which I think is what you wanted.



来源:https://stackoverflow.com/questions/6726130/sorting-a-table-in-descending-order-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!