lua-users home
lua-l archive

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


On Fri, 7 May 2004 01:17:04 +0100
Jamie Webb <j@jmawebb.cjb.net> wrote:

> 
> If I really felt the need to implement logic as a single function rather than 
> a state machine, I might start thinking about preprocessing the Lua code, 
> e.g. to turn this:
> 
>     function my_game()
>         local x = do_stuff()
>         %YIELDPOINT%
>         return do_more_stuff(x)
>     end
> 
> Into this:
> 
>     function my_game()
>         local x = do_stuff()
>         return my_yield(42, x)
>     end
> 
>     continuations[42] = function(x)
>          return do_more_stuff(x)
>     end


This is exactly what coroutines do in Lua 5!

This is facilitated by the fact that Lua 5 is built with an interpreter
that is nonrecursive with respect to the C stack. This is a huge advantage
over nearly every other scripting language its class (some exceptions
would be good implementations of Scheme, the now abandoned classic Stackless
Python, and probably some others I'm not aware of.)

One doesn't need a preprocessor to do this, simply use coroutine.yield(),
and fire off the initial function with a call to coroutine.wrap().

:
> The state machine is the better option though, even if it seems like more 
> marginal work. Really.

Coroutines are powerful precisely because they allow one to use code
written as a thread ("synchronous" or "multithreaded" style) as state
machines, implicitly and cleanly.

In fact, Lua coroutines _are_ state machines. They are state machines
which abstract the workings of the Lua VM itself.

Eric