lua-users home
lua-l archive

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


Wow, wow!

So this is what tail calls are for. This means that there is no threat of stack overflow in a state machine like you suggest, is there? I certainly couldn't get stackoverflow in my quick test based on two functions calling each other. No memory growth either! Very sweet.

Thanks a bunch,
Alex

Roberto Ierusalimschy wrote:

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
   end
   return idle()     -- go throu ;)
end

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

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

-- Roberto