lua-users home
lua-l archive

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

> With multi-threaded scripting languages, especially those for games,
> it is necessary to implement state machines, or more simply put, areas
> of code you can *jump* to, to get a character to go into a particular
> state.

Lua 5 has proper tail calls, which are a form of goto between functions.
If you make each state into a function, you can jump from one to another
with proper tail calls:

function check ()
    nearest_player = check_for_nearest_player();
    if nearest_player then
      return attack()   -- jump_to_state
    return idle()     -- go throu ;)

function idle ()
    play( "scratch_arse" );
    wait( 5 )
    play( "look_around_aimlessly" );
    return check()   -- jump_to_state

function attack ()
    play( "monster_roar" );
    while ( nearest_player == check_for_nearest_player() ) do
        if ( turn_to_player() ) then
            play( "chase_1_step" )
        wait( 1 )     // wait 1 frame (or nth of a second)
    return check()   -- jump_to_state

-- Roberto