From 6b985f65744945785fe8aecf31e89e11ec084389 Mon Sep 17 00:00:00 2001 From: NullBite Date: Mon, 26 Jun 2023 01:33:56 -0400 Subject: [PATCH] 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 --- statemonitor.lua | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 statemonitor.lua 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