我通常可以弄清楚如何在 LUA 中编写我想要的迭代器。
但是递归迭代器让我打败了。
例如,下面是一个返回嵌套列表中所有项目的 Python 递归迭代器:
def items(x):
if isinstance(x,(list,tuple)):
for y in x:
for z in items(y): yield z
else:
yield x
for x in items([10,20,[30,[40,50],60],[70,80]]): print(x)
这会打印
10
20
30
40
50
60
70
80
但是我无法在 Lua 中运行它。我认为这是因为我不知道如何将递归遍历的状态从迭代中的一步转移到下一步。
建议?
最佳答案
FP 风格
local function items(tbl, outer_iter)
local index = 0
local function iter()
index = index + 1
return tbl[index]
end
return
function ()
while iter do
local v = iter()
if v == nil then
iter, outer_iter = outer_iter
elseif type(v) == "table" then
iter = items(v, iter)
else
return v
end
end
end
end
协程风格
local function items(tbl)
return coroutine.wrap(
function()
for _, v in ipairs(tbl) do
if type(v) == "table" then
local iter = items(v)
local v = iter()
while v ~= nil do
coroutine.yield(v)
v = iter()
end
else
coroutine.yield(v)
end
end
end
)
end
使用示例:
for x in items{10,20,{30,{},{40,50},60},{70,80}} do
print(x)
end
关于lua - lua中如何实现递归迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70217201/