Created
October 4, 2015 14:01
-
-
Save dinodeck/5fd84bdff8670964c599 to your computer and use it in GitHub Desktop.
A simple reusable state machine written in Lua.
This file contains 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
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