lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

> It work fine on my box. I translated the comments using Google, but I still
> don't understand how this work, it is black magic for me :-)

coroutine.create(f) creates a coroutine (that part is easy ;-). From
the point of view of Lua, a coroutine is a function. When you call that
function, "f" (the coroutine "body") starts execution (as if you have
called "f" directly).

However, at any point during its execution, "f" may call
"coroutine.yield(...)". (Actually, not only "f", but any function called
by "f".)  At that point, the coroutine stops its execution, and control
goes back to the call to "f" (that is, to the caller it is as if "f"
has returned). But when the caller calls the coroutine again, it continues
its execution from the point where it has yielded. That is, "yield"
suspends the execution of the coroutine, which can be resumed later.

As a simpler example:

function f ()
  for i=1,1000 do

c = coroutine.create(f)

print(c())         --> 1
print(c())         --> 2
print(c())         --> 3
print(c())         --> 4

-- Roberto