lua-users home
lua-l archive

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

Like a little jewel, well hidden beneath the earth surface. ;)

Which brings me -again- back to the book... Either Roberto will educate us infinately here, or, get the book out. :) Or someone else?

It was only Roberto's example that opened my eyes, too, as to what these 'tail calls' actually are. I had thought it to be about tail recursion..


Alex Bilyk kirjoittaa tiistaina, 24. kesäkuuta 2003, kello 20:06:

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,

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

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