knucklebones/states/state_manager.lua

61 lines
1.7 KiB
Lua
Raw Normal View History

2023-08-12 11:36:14 +02:00
--- States stack
--- @class StateManager
StateManager = {
states = {},
---
---@param self StateManager
new = function(self, o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end,
---
---@param self StateManager
---@return unknown
_get_current_state = function(self)
return self.states[#self.states]
end,
---
---@param self StateManager
---@param state any
_set_current_state = function(self, state)
if #self.states == 0 then
self.states = { state }
else
local last = self.states[#self.states]
if last._leave then last:_leave() end
self.states[#self.states] = state
end
end,
---
---@param self StateManager
---@param state any
change_state = function(self, state, ...)
local current = self:_get_current_state()
if current and current._leave then current:_leave() end
self:_set_current_state(state)
if state._enter then state:_enter(...) end
end,
---
---@param self StateManager
push_state = function(self, state, data)
table.insert(self.states, state)
if state._enter then state:_enter(data) end
end,
---
---@param self StateManager
pop_state = function(self)
local state = table.remove(self.states)
if #self.states == 0 then trace("No state left", 2) end
if state._leave then state:_leave() end
end,
---
---@param self StateManager
update = function(self)
local current = self:_get_current_state()
if not current then return end
if current.update then current:update() end
end,
}