暂停迭代

the*_*eta 0 lua

我有Lua表,t我迭代:

for k, v in pairs(t) do
    b = false
    my_func(v)
end
Run Code Online (Sandbox Code Playgroud)

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

Lua有可能吗?

Nic*_*las 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
Run Code Online (Sandbox Code Playgroud)

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