Skip to main content
Tweeted twitter.com/#!/StackGameDev/status/115635934996860928

Game State Management using LUALua

Source Link

Game State Management using LUA

I want to be able to (only) define game states using Lua script, but I'm not sure how I should do it. Here's what I have in mind currently:

For each state, I will create a .lua file that contains a class (table) that has the same name as the file name. Each table must have a set of event handlers: onEnter (called when the state is entered), onUpdate (called every frame) and onExit (called when exiting the state). So if I want to have a MainMenuState, I will have a file called "MainMenuState.lua" which will contain something like this:

MainMenuState = {}

MainMenuState["onEnter"] = function()
end

MainMenuState["onUpdate"] = function(elapsedTime)
end

MainMenuState["onExit"] = function()
end

Defined states will be exposed to the game engine via a singleton StateManager class. StateManager will have a function that registers a state under a unique name:

void registerState(string stateName, string fileName);

State registration will be done in script by placing the registration codes inside an init script that is called once after the game engine is initialized:

--init.lua
--Register all the states needed by the game
StateManager:registerState("SplashScreen", "SplashScreen.lua")
StateManager:registerState("MainMenuState", "MainMenuState.lua")
StateManager:registerState("InGameState", "InGameState.lua")
-- etc etc

StateManager will also keep track of which state is currently active and also handle state transitions:

//cpp
void changeState(string state);

--lua
StateManager:changeState("PauseMenuState")