按键对 Lua 表进行排序 [英] Sorting a Lua table by key
问题描述
我已经浏览了很多问题和 Google 结果,但找不到解决方案.
I have gone through many questions and Google results but couldn't find the solution.
我正在尝试使用 Lua 中的 table.sort
函数对表格进行排序,但我不知道如何使用它.
I am trying to sort a table using table.sort
function in Lua but I can't figure out how to use it.
我有一个表,其键是随机数值.我想按升序对它们进行排序.我也浏览了 Lua wiki 页面,但 table.sort
仅适用于表值.
I have a table that has keys as random numeric values. I want to sort them in ascending order. I have gone through the Lua wiki page also but table.sort
only works with the table values.
t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" }
我想要它:
t = { [7]="qwe", [23]="fgh", [223]="asd", [543]="hjk" }
推荐答案
您无法使用 pairs
设置从散列(即您的表的内容)中检索元素的顺序.您需要从该表中获取键,将键作为自己的表进行排序,然后使用这些排序的键从原始表中检索值:
You cannot set the order in which the elements are retrieved from the hash (which is what your table is) using pairs
. You need to get the keys from that table, sort the keys as its own table, and then use those sorted keys to retrieve the values from your original table:
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
这将打印
7 qwe
23 fgh
223 asd
543 hjk
另一种选择是提供您自己的迭代器而不是 pairs
以按您需要的顺序迭代表,但键的排序可能足以满足您的需要.
Another option would be to provide your own iterator instead of pairs
to iterate the table in the order you need, but the sorting of the keys may be simple enough for your needs.
这篇关于按键对 Lua 表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!