sorting a table in descending order in Lua

落花浮王杯 提交于 2019-12-08 23:26:32

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.

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