Sorting a Lua table by key
我经历了许多问题和Google结果,但找不到解决方案。
我试图在Lua中使用
我有一个表,其中的键为随机数值。 我想按升序对它们进行排序。 我也浏览了Lua Wiki页面,但是
1 | t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" } |
我想要这样:
1 | t = { [7]="qwe", [23]="fgh", [223]="asd", [543]="hjk" } |
您不能使用
1 2 3 4 5 6 7 8 | local t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" } local tkeys = {} -- populate the table that holds the keys for k in pairs(t) do table.insert(tkeys, k) end -- sort the keys table.sort(tkeys) -- use the keys to retrieve the values in the sorted order for _, k in ipairs(tkeys) do print(k, t[k]) end |
这将打印
1 2 3 4 | 7 qwe 23 fgh 223 asd 543 hjk |
另一个选择是提供您自己的迭代器而不是
@lhf所说的是正确的,您的lua表以实现可行的顺序保存其内容。但是,如果要以排序的方式打印(或遍历),则可以(因此可以逐个比较它)。为此,您可以按照以下方式进行操作
1 2 3 | for key, value in orderedPairs(mytable) do print(string.format("%s:%s", key, value)) end |
不幸的是,lua的一部分未提供orderedPairs,但是您可以从此处复制实现。
Lua表中没有顺序的概念:它们只是键值对的集合。
下面的两个表具有完全相同的内容,因为它们包含完全相同的对:
1 2 | t = { [223] ="asd" ,[23] ="fgh",[543]="hjk",[7]="qwe"} t = {[7]="qwe",[23] ="fgh",[223] ="asd" ,[543]="hjk"} |