Created
October 5, 2017 03:40
-
-
Save Philanatidae/177f858925ea089838b3c74859c30aa9 to your computer and use it in GitHub Desktop.
Basic state machine in Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- States | |
| stateA = {} | |
| function stateA:onStart() | |
| -- Called when state is switched to this state | |
| end | |
| function stateA:render(dt) | |
| -- Called every frame | |
| end | |
| function stateA:onEnd() | |
| -- Called when state is switched from this state | |
| end | |
| stateB = {} | |
| function stateB:onStart() | |
| -- Called when state is switched to this state | |
| end | |
| function stateB:render(dt) | |
| -- Called every frame | |
| end | |
| function stateB:onEnd() | |
| -- Called when state is switched from this state | |
| end | |
| -- State Machine | |
| stateMachine = {} | |
| stateMachine._activeState = nil | |
| function stateMachine:switchState(newState) | |
| if self._activeState ~= nil then | |
| self._activeState:onEnd() -- Tell old state it's ended | |
| end | |
| self._activeState = newState | |
| self._activeState:onStart() | |
| end | |
| function stateMachine:render(dt) | |
| if self._activeState ~= nil then | |
| self._activeState:render(dt) | |
| end | |
| end | |
| -- In your game logic | |
| stateMachine:switchState(stateA) -- Initial state, stateA | |
| stateMachine:switchState(stateB) -- Switch to different states like so | |
| stateMachine:switchState(stateA) -- And back, if you so wish | |
| -- In your game's render loop | |
| stateMachine:render(dt) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment