You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中实现递归迭代器?参照Python嵌套列表遍历示例

Lua 递归嵌套列表迭代器实现方案

方案1:基于协程实现(最贴近Python生成器逻辑)

Lua的协程原生支持执行挂起/恢复,和Python生成器的yield逻辑完全对齐,代码写法和你给出的Python版本高度一致:

local function items(x)
    return coroutine.wrap(function()
        if type(x) == "table" then
            for _, y in ipairs(x) do
                for z in items(y) do
                    coroutine.yield(z)
                end
            end
        else
            coroutine.yield(x)
        end
    end)
end

-- 测试调用
for x in items({10,20,{30,{40,50},60},{70,80}}) do
    print(x)
end

运行输出和Python版本完全相同:

10
20
30
40
50
60
70
80

方案2:手动维护状态栈(无协程版本)

如果不想依赖协程,可以手动维护遍历栈传递递归状态,实现纯原生的迭代器:

local function items(x)
    -- 栈存储待遍历的表和当前遍历下标
    local stack = {{tbl = x, idx = 1}}
    return function()
        while #stack > 0 do
            local curr = stack[#stack]
            local val = curr.tbl[curr.idx]
            curr.idx = curr.idx + 1
            if val == nil then
                -- 当前表遍历完,弹出栈
                table.remove(stack)
            else
                if type(val) == "table" then
                    -- 遇到子表压入栈顶,优先遍历
                    table.insert(stack, {tbl = val, idx = 1})
                else
                    -- 非表元素直接返回
                    return val
                end
            end
        end
        -- 栈空迭代结束
        return nil
    end
end

-- 测试调用和方案1一致,输出相同
for x in items({10,20,{30,{40,50},60},{70,80}}) do
    print(x)
end

内容的提问来源于stack exchange,提问作者Tim Menzies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:27:05