【问题标题】:Lua ordered table iterationLua有序表迭代
【发布时间】:2015-09-07 14:57:51
【问题描述】:

我需要按照创建的顺序遍历 Lua 表。我找到了这篇文章 - http://lua-users.org/wiki/SortedIteration 但它似乎不起作用:

function __genOrderedIndex( t )
local orderedIndex = {}
for key in pairs(t) do
    table.insert( orderedIndex, key )
end
table.sort( orderedIndex )
return orderedIndex
end

function orderedNext(t, state)
-- Equivalent of the next function, but returns the keys in the alphabetic
-- order. We use a temporary ordered key table that is stored in the
-- table being iterated.

key = nil
--print("orderedNext: state = "..tostring(state) )
if state == nil then
    -- the first time, generate the index
    t.__orderedIndex = __genOrderedIndex( t )
    key = t.__orderedIndex[1]
else
    -- fetch the next value
    for i = 1,table.getn(t.__orderedIndex) do
        if t.__orderedIndex[i] == state then
            key = t.__orderedIndex[i+1]
        end
    end
end

if key then
    return key, t[key]
end

-- no more value to return, cleanup
t.__orderedIndex = nil
return
end

function orderedPairs(t)
    return orderedNext, t, nil
end

以下是使用示例:

t = {
['a'] = 'xxx',
['b'] = 'xxx',
['c'] = 'xxx',
['d'] = 'xxx',
['e'] = 'xxx',
}


for key, val in orderedPairs(t) do
   print(key.." : "..val)
end

我收到一个错误:

尝试调用字段“getn”(零值)

有什么问题?

【问题讨论】:

标签: lua lua-table


【解决方案1】:

table.getn 自 Lua 5.1 起已被删除,取而代之的是 # 运算符。

table.getn(t.__orderedIndex) 更改为#t.__orderedIndex

【讨论】:

  • 如果我需要按创建顺序进行迭代怎么办。有可能吗?
  • 订单未指定。如果您有新问题,请提出新问题。
  • 非常感谢,新问题来了 - stackoverflow.com/questions/32451755/… 。非常感谢您的帮助。
猜你喜欢
  • 2012-09-15
  • 1970-01-01
  • 2012-05-27
  • 2015-05-31
  • 2017-05-11
  • 2017-10-17
  • 2018-06-06
  • 2017-12-08
  • 1970-01-01
相关资源
最近更新 更多