Added State Change Callback Functions

Each state now has an OnOpen and OnClose callback function. These are available to be set by the client but not required. If not set, they will be ignored.
This commit is contained in:
Centauri Soldier 2021-04-07 12:52:43 -07:00
parent eae3c6edbe
commit 5e86bbb0b6

View File

@ -5,18 +5,74 @@
return function(loveframes) return function(loveframes)
---------- module start ---------- ---------- module start ----------
-- util library -- util library
--local util = {} --local util = {}
local statecallbacks = {};
--[[--------------------------------------------------------- --[[---------------------------------------------------------
- func: SetState(name) - func: SetState(name)
- desc: sets the current state - desc: sets the current state
--]]--------------------------------------------------------- --]]---------------------------------------------------------
function loveframes.SetState(name) function loveframes.SetState(name)
loveframes.state = name if (loveframes.state ~= name) then
loveframes.base.state = name
--fire the closing function of the soon-to-be-closed state
if (type(statecallbacks[loveframes.state]) == "table" and
type(statecallbacks[loveframes.state].onclose) == "function") then
--callback must accept the name of the current state and soon-to-be-opened state as args
statecallbacks[loveframes.state].onclose(loveframes.state, name);
end
local oldstate = loveframes.state;
loveframes.state = name
loveframes.base.state = name
--fire the opening function of the newly-opened state
if (type(statecallbacks[loveframes.state]) == "table" and
type(statecallbacks[loveframes.state].onopen) == "function") then
--callback must accept the name of the current state and previous state as args
statecallbacks[loveframes.state].onopen(name, oldstate);
end
end
end
--[[---------------------------------------------------------
- func: SetStateOnOpenCallback(name, func)
- desc: sets a state's opening callback function
--]]---------------------------------------------------------
function loveframes.SetStateOnOpenCallback(name, func)
if (type(name) == "string" and name:gsub("%s", '') ~= '' and
type(func) == "function") then
if (not (statecallbacks[name])) then
statecallbacks[name] = {};
end
statecallbacks[name].onopen = func;
end
end
--[[---------------------------------------------------------
- func: SetStateOnOpenCallback(name, func)
- desc: sets a state's closing callback function
--]]---------------------------------------------------------
function loveframes.SetStateOnCloseCallback(name, func)
if (type(name) == "string" and name:gsub("%s", '') ~= '' and
type(func) == "function") then
if (not (statecallbacks[name])) then
statecallbacks[name] = {};
end
statecallbacks[name].onclose = func;
end
end end