【问题标题】:Sorting multidimensional table in Lua在 Lua 中对多维表进行排序
【发布时间】: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,因此误解了这个问题。所以您的解决方案应该可以工作,您可以将其发布为答案。

标签: sorting lua lua-table


【解决方案1】:

稍微解释一下:

#table 不一定返回表的长度。如果添加到没有特殊键的表中,表元素将获得默认键。这些键从 1 开始直到 n。如果两个键之间存在间隙,当您提供自己的键时,#table 将返回该间隙之前的键。 示例:

t = {'one', 'two', 'three'} -- would be a table like 1 - one, 2 - two, 3 - three
print(#t) -- the last key -> 3, here it works
t2 = {'one', 'two', [4] = 'four'} -- would be a table like 1 - one, 2 - two, 4 - four
print(#t2) -- the last key without a gap -> 2, does not work

pairs(table) 和 ipairs(table) 也是如此。 ipairs 从键 1 迭代到 n 没有间隙,pairs 迭代所有键。这就是解决方案有效的原因。 您可以为表 (__len) 设置自己的元方法以使用 # 来获得正确的长度。

请记住,您的表键默认从 1 开始。 希望它有助于理解这里的问题。

【讨论】:

    【解决方案2】:

    解决方案

    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
    

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 2013-03-20
      • 2011-10-07
      • 2014-08-01
      • 2013-03-21
      • 1970-01-01
      • 2010-10-13
      • 2011-10-29
      相关资源
      最近更新 更多