Skip to content

Instantly share code, notes, and snippets.

@Philanatidae
Created October 5, 2017 03:40
Show Gist options
  • Select an option

  • Save Philanatidae/177f858925ea089838b3c74859c30aa9 to your computer and use it in GitHub Desktop.

Select an option

Save Philanatidae/177f858925ea089838b3c74859c30aa9 to your computer and use it in GitHub Desktop.
Basic state machine in Lua
-- 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