nulllib-lua/statemonitor.lua
NullBite 6b985f6574
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
2023-06-26 01:33:56 -04:00

44 lines
1.1 KiB
Lua

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