theta
theta

Reputation: 25611

Pause iteration

I have Lua table, t, which I iterate:

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

and want iteration to pause until b global variable changes to true

Is it possible is Lua?

Upvotes: 0

Views: 185

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473577

Unless you're in a coroutine, there's no concept of a Lua variable changing value without your code doing it. So you would be pausing until something that can't possibly happen happens. Lua is inherently single-threaded.

As previously stated, you can use a coroutine to do this, but you'll have to modify your code accordingly:

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

Note that changing the table referenced by t between iterations is not going to do something useful.

Upvotes: 6

Related Questions