暂停迭代

时间:2012-04-09 00:55:33

标签: lua

我有Lua表t,我迭代了:

for k, v in pairs(t) do
    b = false
    my_func(v)
end

并希望迭代暂停,直到b全局变量更改为true

Lua可能吗?

1 个答案:

答案 0 :(得分:6)

除非你是一个协程,否则没有一个Lua变量值的概念没有你的代码就可以了。所以你会暂停,直到不可能发生的事情发生。 Lua本质上是单线程的。

如前所述,您可以使用协程执行此操作,但您必须相应地修改代码:

function CoIterateTable(t)
  for k, v in pairs(t) do
    b = false
    my_func(v)

    while(b == false) do coroutine.yield() end
  end
end

local co = coroutine.create(CoIterateTable)

assert(co.resume(t))
--Coroutine has exited. Possibly through a yield, possibly returned.
while(co.running()) do
  --your processing between iterations.
  assert(co.resume(t))
end

请注意,在迭代之间更改t引用的表不会有用。

相关问题