Please note that I don't update this web site anymore. You can visit my new personal blog at www.williamwilling.com.
Proper Tail Calls
Thursday, June 30, 2005
I know I promised to write an article about the game loop and game states, but it takes a bit more time than I expected. I will make good on my promise, though. In the mean time, here is something to consider.
While learning a bit about Lua, I read about proper tail calls. It seems to me proper tail calls would be absolutely marvelous when dealing with game states.
Consider this C-like pseudocode.
void MainMenuState()
{
while (true)
{
// ...
switch (key)
{
case P:
return PlayState();
case ESCAPE:
return;
}
// ...
}
}
void PlayState()
{
while (true)
{
// ...
switch (key)
{
case ESCAPE:
return MainMenuState();
}
if (win || lose)
return MainMenuState();
// ...
}
}
In C (or C++) this would seem to work at first glance, but after switching between MainMenuState()
and PlayState()
a couple of times, you'll get a stack overflow or run out of memory. When MainMenuState()
calls PlayState()
, its local variables stay on the stack until PlayState()
returns, which it never does. Instead, PlayState()
calls MainMenuState()
when it's done. PlayState()
's local variables remain on the stack and MainMenuState()
reserves new stack space, so there are now two MainMenuState()
-stacks. Trouble looms.
Things aren't quite as gloomy in Lua. Lua actually recognizes that MainMenuState()
doesn't have to do anything after the call to PlayState()
and that it therefor doesn't need its stack anymore. In a manner of speaking, MainMenuState()
exits just before PlayState()
is called, not after. Neat. :-)
Using proper tail calls this way, you wouldn't need a game state manager. I wonder what impact it has on resource management, though.
Back to blog index
Wouter Lindenhof says:
I was wondering....
Did you make the menu first and build the actually game in it or did you do it the other way around?
I myself did the game first and am now building the menu around it. There is only one problem, though. I'm starting to handle input on more than one location and now since I'm lazy also start handeling action one more than one location. Yes, it's bad. But since I'm still testing my system I don't mind.
What has your experience been on that? (I mean how did you do it and what did you think about it?)
Sunday, July 3, 2005 1:18 PM
Joost Ronkes Agerbeek says:
If I recall correctly, I built the main menu first. The order doesn't really matter, though, since I use what are called game states. I will write about this, really, but there is just so much to cover and I want to do it properly. This topic gets very little coverage on the web or in game programming books. The only useful information I know of is at http://tonyandpaige.com/tutorials/game1.html
Monday, July 4, 2005 7:23 PM
Tell me what you think
Since I'm not updating this site anymore, I disabled comments. You can visit me at my new site: www.williamwilling.com.