From 45cbda810d8f0984658d1236ce048994c5b899f6 Mon Sep 17 00:00:00 2001 From: grilledham Date: Sat, 7 Apr 2018 00:24:16 +0100 Subject: [PATCH] experimental removable events --- utils/event.lua | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/utils/event.lua b/utils/event.lua index 2d51fbef..926260bc 100644 --- a/utils/event.lua +++ b/utils/event.lua @@ -5,6 +5,8 @@ local debug_mode = false local init_event_name = -1 local load_event_name = -2 +local control_stage = true + local event_handlers = {}-- map of event_name to handlers[] local on_nth_tick_event_handlers = {}-- map of nth_tick to handlers[] @@ -83,4 +85,68 @@ function Event.on_nth_tick(tick, handler) end end +local Token = require "utils.global_token" +global.event_tokens = {} + +function Event.add_removable(event_name, token) + local event_tokens = global.event_tokens + + local tokens = event_tokens[event_name] + if not tokens then + event_tokens[event_name] = {token} + else + table.insert(tokens, token) + end + + if not control_stage then + local handler = Token.get(token) + Event.add(event_name, handler) + end +end + +local function remove(t, e) + for i, v in ipairs(t) do + if v == e then + table.remove(t, i) + break + end + end +end + +function Event.remove_removable(event_name, token) + local event_tokens = global.event_tokens + + local tokens = event_tokens[event_name] + + if not tokens then + return + end + + local handler = Token.get(token) + local handlers = event_handlers[event_name] + + remove(tokens, token) + remove(handlers, handler) + + if #handlers == 0 then + script.on_event(event_name, nil) + end +end + +local function add_token_handlers() + control_stage = false + + local event_tokens = global.event_tokens + + for event_name, tokens in pairs(event_tokens) do + for _, token in ipairs(tokens) do + local handler = Token.get(token) + Event.add(event_name, handler) + end + end +end + +Event.on_init(add_token_handlers) +Event.on_load(add_token_handlers) + return Event