Skip to content

Instantly share code, notes, and snippets.

@dinodeck
Created October 4, 2015 14:01
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinodeck/5fd84bdff8670964c599 to your computer and use it in GitHub Desktop.
Save dinodeck/5fd84bdff8670964c599 to your computer and use it in GitHub Desktop.
A simple reusable state machine written in Lua.
StateMachine = {}
StateMachine.__index = StateMachine
function StateMachine:Create()
local this =
{
mEmpty =
{
HandleInput = function() end,
Update = function() end,
Enter = function() end,
Exit = function() end
},
mCurrent = nil,
mStates = {}
}
this.mCurrent = this.mEmpty
setmetatable(this, self)
return this
end
function StateMachine:Change(stateName, enterParams)
assert(self.mStates[stateName]) -- state must exist!
self.mCurrent:Exit()
self.mCurrent = self.mStates[stateName]
self.mCurrent:Enter(enterParams)
end
function StateMachine:Update(dt)
self.mCurrent:Update(dt)
end
function StateMachine:Add(id, state)
self.mStates[id] = state
end
function StateMachine:Remove(id)
if self.mCurrent == self.mStates[id] then
self.mCurrent = self.mEmpty
end
self.mStates[id] = nil
end
function StateMachine:Clear()
self.mStates = {}
self.mCurrent = self.mEmpty
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment