lua-users home
lua-l archive

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


I must say, that's the easiest to follow explanation of coroutines I've seen
yet. I see how they could be extremely useful... game logic that has
per-frame time limits come to mind.

--James Hearn

> 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
>     coroutine.yield(i)
>   end
> end
>
> c = coroutine.create(f)
>
> print(c())         --> 1
> print(c())         --> 2
> print(c())         --> 3
> print(c())         --> 4
>   ...
>
> -- Roberto