Merge pull request #13 from CentauriSoldier/master

Added State Change Callback Functions
This commit is contained in:
Caldas Lopes 2021-04-08 19:24:30 +01:00 committed by GitHub
commit 96dd0de7ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,18 +5,74 @@
return function(loveframes)
---------- module start ----------
-- util library
--local util = {}
local statecallbacks = {};
--[[---------------------------------------------------------
- func: SetState(name)
- desc: sets the current state
--]]---------------------------------------------------------
function loveframes.SetState(name)
loveframes.state = name
loveframes.base.state = name
if (loveframes.state ~= name) then
--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