Created
February 8, 2024 07:56
-
-
Save jmiskovic/ac370f0629a613403c5e88552e4930d3 to your computer and use it in GitHub Desktop.
Tiny Lua stage management 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
-- manages "stages" with a stack interface | |
-- stage is Lua module with callbacks (load, update, draw, keypress...) | |
-- only single stage is active, one on top of the stack | |
-- after push and pop operation another stage takes over the callbacks | |
-- example stack: os > main_menu > level_selection > game_play > overlay_menu | |
-- example usage: | |
-- local stagestack = require'stagestack' | |
-- stagestack.push(require'main_menu') | |
local m = {} | |
m.stack = {} | |
m.active = nil | |
m.loaded = {} | |
local callbacks = { | |
-- not touched 'conf', 'load', 'log', 'mirror', | |
-- 'errhand', 'threaderror', | |
'update', 'draw', | |
'keypressed', 'keyreleased', 'textinput', | |
'mousepressed', 'mousemoved', 'mousereleased', 'wheelmoved', | |
'quit', 'restart', | |
'focus', 'resize', | |
'permission', | |
} | |
local function switch(stage) | |
if not stage then | |
lovr.event.quit() | |
end | |
if not m.loaded[stage] then | |
if stage.load then | |
stage.load() | |
end | |
m.loaded[stage] = true | |
end | |
for i, callback in ipairs(callbacks) do | |
lovr[callback] = stage[callback] or lovr[callback] | |
end | |
m.active = stage | |
end | |
function m.push(stage) | |
table.insert(m.stack, stage) | |
switch(stage) | |
end | |
function m.pop() | |
local stage = table.remove(m.stack) | |
switch(m.stack[#m.stack]) | |
return stage | |
end | |
return m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment