diff --git a/statemonitor.lua b/statemonitor.lua new file mode 100644 index 0000000..5536924 --- /dev/null +++ b/statemonitor.lua @@ -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