statemonitor: to register callbacks to state
It takes two functions; one is to check the state and the other is a callback to execute if the first function evaluates true. It can automatically handling deregistering functions once they are no longer needed
This commit is contained in:
parent
72f20234f0
commit
6b985f6574
43
statemonitor.lua
Normal file
43
statemonitor.lua
Normal file
@ -0,0 +1,43 @@
|
||||
local statemonitor={}
|
||||
|
||||
local callbacks={}
|
||||
|
||||
local function ternary(val, t, f)
|
||||
if val then return t else return f end
|
||||
end
|
||||
|
||||
--- Deregister a callback
|
||||
---@param name string Name of callback
|
||||
function statemonitor.deregister(name)
|
||||
callbacks[name] = nil
|
||||
end
|
||||
|
||||
--- Register a callback to a function
|
||||
--Registers a callback to run when a check funciton evaluates to true
|
||||
---@param name string Name of callback
|
||||
---@param check function Function to evaluate
|
||||
---@param callback function Callback to run when true
|
||||
---@param frequency? integer Frequency to run the check, in ticks (default 5)
|
||||
---@param once? boolean Whether the callback should be deregistered after running once, default true
|
||||
function statemonitor.register(name, check, callback, frequency, once)
|
||||
frequency=frequency or 5
|
||||
once=ternary(once ~= nil, once, true)
|
||||
callbacks[name] = {check=check, callback=callback, f=frequency,
|
||||
deregister=once}
|
||||
end
|
||||
|
||||
local function tick()
|
||||
for k, v in pairs(callbacks) do
|
||||
if world.getTimeOfDay() % v.f and v.check() then
|
||||
v.callback()
|
||||
if v.deregister then
|
||||
statemonitor.deregister(k)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
events.TICK:register(tick, "nulllib.statemonitor")
|
||||
|
||||
|
||||
return statemonitor
|
Loading…
x
Reference in New Issue
Block a user