lua - lua中如何实现递归迭代器?

标签 lua iterator

我通常可以弄清楚如何在 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/

相关文章:

java - 倒带迭代器

c - 将只读缓冲区从 C 传递给 Lua

lua - 在Lua中模拟并行

lua - 如何将 os.execute ("dir") 中的目录信息保存到字符串中?

c++ - boost中的数字范围迭代器?

python - 'numpy.float64' 对象不可迭代

autocomplete - 是否有任何适用于 Mac 的文本编辑器可以配置为具有或已经具有 Lua 自动完成功能?

syntax - 是否可以从 luaL_loadstring 等获取有关语法错误发生位置的更多信息?

c++ - 如果找不到元素,std::find 返回什么

python - 如何实现自定义迭代器以便可以嵌套它们?