我需要按照 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
我收到错误:
attempt to call field 'getn' (a nil value)
问题是什么?
最佳答案
table.getn
自 Lua 5.1 起已被删除,由 #
运算符取代。
将table.getn(t.__orderedIndex)
更改为#t.__orderedIndex
。
关于Lua 有序表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32441520/