0

我有 Lua 表,t我对其进行了迭代:

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

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

有可能是Lua吗?

4

1 回答 1

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在迭代之间更改引用的表不会做任何有用的事情。

于 2012-04-09T01:13:52.327 回答