【发布时间】:2014-10-13 10:22:13
【问题描述】:
“如何在 Lua 中对表格进行排序”这个问题并不新鲜,但我找到的答案并不能帮助我,也许你可以。
我得到了这张桌子:
table = {} -- some kind of database
table[1] = {table.containing.table.with.even.more.tables.inside}
table[9] = {table.containing.table.with.even.more.tables.inside}
table[13] = {table.containing.table.with.even.more.tables.inside}
table[15] = {table.containing.table.with.even.more.tables.inside}
table[45] = {table.containing.table.with.even.more.tables.inside}
table[3254] = {table.containing.table.with.even.more.tables.inside}
现在我想遍历“表”,检查它包含的指定布尔值,如果是,则使用来自某些子表的参数运行一个方法。
for key, value in pairs(table) do
print(key)
end
类似于:
9 13 1 3254 45 15
据我所知,这是因为 Lua 遍历哈希值(对吗?)。
我的想法是:
sorted_table = {} -- shall point to table, with sorted keys
for i = 0, #table do -- from 0 to the last key of table (some write #table is the last key, some write it's the number of contained keys, I don't know. If you do, please tell me.)
if table[i] then -- for runs every number from i to #table, if i is a key, bingo.
table.insert(sorted_table,(table[i])) -- first key found -> sorted_table[1], second -> sorted_table[2]....
end
end
for k,v in pairs(sorted_table) do
print(key)
end
我没有出错,它只是跳过了函数,没有任何反应。当我打印#table 时,它会打印0。 #table 在另一个文件中,但它不是本地文件,而是在函数文件中的其他位置使用,所以,.. 这很奇怪。
编辑 嗯奇怪。我进行了一些调试,#table 为 nil,但在代码下方的 pair(table) 中,一切正常。
**SOLUTION-EDIT**
local sorted_table = {}
for k, v in pairs(original_table) do
table.insert(sorted_table, k)
end
table.sort(sorted_table)
for k, v in ipairs(sorted_table) do
print(original_table[v])
end
【问题讨论】:
-
我只看到了你的代码(它在新表中添加了值
table[i],而不是键),没有看到评论-- shall point to table, with sorted keys,因此误解了这个问题。所以您的解决方案应该可以工作,您可以将其发布为答案。