• Subject: eyes opened (tail recursion)
• Date: Tue, 24 Jun 2003 23:28:42 +0300

```
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..
```
-ak

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,
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

```
```

```
```

```