在Lua中以降序对表进行排序 [英] sorting a table in descending order in Lua

查看:645
本文介绍了在Lua中以降序对表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法正常工作:

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

遇到此错误:尝试比较两个nil值

Getting this error: attempt to compare two nil values

这是 lua中表值排序的后续操作

推荐答案

如何?

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

以这种方式组织数据使排序更容易,并且请注意,我只调用一次table.sort,而不是对表的每个元素调用一次.我根据子表中的第二个值进行排序,我认为这是您想要的.

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.

这篇关于在Lua中以降序对表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆