lua中的表值排序 [英] table value sorting in lua
问题描述
我有一张这样的桌子:
tbl = {
['etc1'] = 1337,
['etc2'] = 14477,
['etc3'] = 1336,
['etc4'] = 1335
}
现在我需要对这张表进行排序,以将输出从高位转换为最低值:
And now I need to sort this table to get output from highes to lowest value:
tbl = {
['etc2'] = 14477,
['etc1'] = 1337,
['etc3'] = 1336,
['etc4'] = 1335
}
已经尝试了很多功能,例如table.sort或官方手册中的其他功能,但没有任何帮助.所以希望你能帮帮我!
Already tried lots of functions like table.sort or others from the official manual, but nothing helped. So hope you'll help me out guys!
致谢.
推荐答案
Lua表除通过其键进行排序外没有其他排序.您将需要像这样更结构化数据:
Lua tables do not have ordering other than by their keys. You will need to structure your data more like this:
tbl = {
[1] = { ['etc2'] = 14477 },
[2] = { ['etc1'] = 1337 },
[3] = { ['etc3'] = 1336 },
[4] = { ['etc4'] = 1335 }
}
或者这个:
tbl = {
[1] = { 'etc2', 14477 },
[2] = { 'etc1', 1337 },
[3] = { 'etc3', 1336 },
[4] = { 'etc4', 1335 }
}
或此,如果要与原始表一起使用:
or this, if you want to use it in conjunction with the original table:
tbl_keys = {
[1] = 'etc2',
[2] = 'etc1',
[3] = 'etc3',
[4] = 'etc4'
}
请注意,我非常明确,并写下了所有数字索引.您当然可以省略它们,所以最后的解决方案是:
Note that I was very explicit and wrote all the numeric indices. You can of course omit them, so the last solution would be:
tbl_keys = {
'etc2',
'etc1',
'etc3',
'etc4'
}
也许这意味着您应该编写一个函数,将原始数据转换为这种新形式,或者您可以在表格首次创建之前就将其完成.
Maybe this means you should write a function which turns the original data into this new form, or maybe you can get it done earlier on, before the table is made in the first place.
这篇关于lua中的表值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!