1
0
mirror of https://github.com/Refactorio/RedMew.git synced 2025-01-18 03:21:47 +02:00

experimental removable events

This commit is contained in:
grilledham 2018-04-07 00:24:16 +01:00
parent 77d4fc9c4a
commit 45cbda810d

View File

@ -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