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
收到此错误:尝试比较两个零值
这是 lua中表值排序
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个怎么样?
以这种方式组织数据可以更轻松地排序,请注意,我只调用
table.sort
一次,而不是表的每个元素调用一次。我根据子表中的第二个值进行排序,我认为这就是您想要的。How about this?
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.