lua-users home
lua-l archive

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


In other words, there is no real multi-tasking in Lua.  Just this
co-routine toy stuff... What would be truly useful is for the embedding
C program to be able to launch several different Lua scripts, which task
switch among themselves, and also allow the C program to run (either
using an update callback called once per schedular run, or by returning
from the schedular and requiring the C program to call into it again).

This could be really useful where bunches of long-running incremental
tasks need to be done (updating a database, for example) or
time-gobbling tasks than require constant "progress" (multiple A*
searches).

I've seen a few patches around that supposedly pull this off.  I'm
curious why such functionality is not yet in Lua.

On Fri, 2002-06-07 at 10:48, Roberto Ierusalimschy wrote:
> > 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
>     coroutine.yield(i)
>   end
> end
> 
> c = coroutine.create(f)
> 
> print(c())         --> 1
> print(c())         --> 2
> print(c())         --> 3
> print(c())         --> 4
>   ...
> 
> -- Roberto