Created
October 10, 2016 22:54
-
-
Save tollyx/9c7ce39adfb9797e6c6ffd573e5ffaa7 to your computer and use it in GitHub Desktop.
Very basic, probably bad in some way gamestate module
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
local gamestates = {} | |
gamestates.debug = false | |
function gamestates:init (initialstate) | |
self.stack = {} | |
self.num = 0 | |
self:clear(initialstate) | |
end | |
function gamestates:update (dt) | |
assert(self.num > 0, "The state stack is empty.") | |
self.stack[self.num]:update(dt) | |
-- debug | |
if imgui and self.debug then | |
imgui.SetNextWindowPos(50, 50, "FirstUseEver") | |
imguistatus, self.debug = imgui.Begin("Gamestates", true, {"AlwaysAutoResize"}); | |
imgui.Text("States in stack: "..self.num) | |
for i=self.num,1,-1 do | |
imguistatus, self.stack[i].debug = imgui.Checkbox(self.stack[self.num].state, self.stack[i].debug) | |
end | |
imgui.End() | |
end | |
end | |
function gamestates:draw () | |
assert(self.num > 0, "The state stack is empty.") | |
self.stack[self.num]:draw() | |
end | |
function gamestates:keypressed (...) | |
assert(self.num > 0, "The state stack is empty.") | |
if self.stack[self.num].keypressed then | |
self.stack[self.num]:keypressed(...) | |
end | |
end | |
function gamestates:push (state, ...) | |
assert(state, "Tried to push a falsy state.") | |
if self.stack[self.num].pause then | |
self.stack[self.num]:pause(state) | |
end | |
if state.enter then | |
state:enter(self.stack[self.num], ...) | |
end | |
self.num = self.num+1 | |
self.stack[self.num] = state | |
end | |
function gamestates:pop () | |
assert(self.num > 1, "Tried to pop the final state.") | |
local previous = self.stack[self.num] | |
self.stack[self.num] = nil | |
self.num = self.num-1 | |
if previous.exit then | |
previous:exit(self.stack[self.num]) | |
end | |
if self.stack[self.num].resume then | |
self.stack[self.num]:resume(previous) | |
end | |
return previous | |
end | |
function gamestates:clear (newstate, ...) | |
assert(newstate, "Tried to clear the stack to a falsy state.") | |
local previous | |
for i=self.num,1,-1 do | |
self.stack[i]:exit() | |
previous = self.stack[i] | |
self.stack[i] = nil | |
if i ~= 1 then | |
self.stack[i-1]:resume(previous) | |
end | |
end | |
self.stack = {newstate} | |
self.num = 1 | |
if self.stack[1].enter then | |
self.stack[1]:enter(nil, ...) | |
end | |
end | |
return gamestates |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment