Lua 有序表迭代

标签 lua lua-table

我需要按照 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/

相关文章:

lua - 为什么短调用形式不适用于 Lua 5.3 中的表?

lua - 如何在lua中使用返回表的函数?

c - 从 C/C++/Rust 设置 lua 表的方法

if-statement - Love2D If# of i,v 表中

objective-c - 我可以假设并处理 Objective-C 中的 SEL 作为指向某物的指针吗?

pdf - Lua 语法高亮 arXiv 的 Latex

function - 在 ipairs() 中使用函数时,LÖVE 崩溃

lua - 什么是弱引用?

Lua, if 语句成语

lua - 检查任意级别是否存在 Lua 表成员