forked from mspielberg/factorio-railloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Event.lua
85 lines (72 loc) · 1.86 KB
/
Event.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local M = {}
--[[
handlers[event_id] = { [handler1] = true, [handler2] = true, ... }
]]
local handlers_for = {}
local function dispatch(event)
for handler in pairs(handlers_for[event.name]) do
handler(event)
end
end
--[[
nth_tick_handlers_for[interval] = { [handler1] = true, ... }
]]
local nth_tick_handlers_for = {}
local function dispatch_nth_tick(event)
for handler in pairs(nth_tick_handlers_for[event.nth_tick]) do
handler(event)
end
end
function M.register(events, handler)
if type(events) ~= "table" then
events = {events}
end
for _, event_id in ipairs(events) do
-- debug("registering for " .. (event_names[event_id] or event_id))
local handlers = handlers_for[event_id]
if not handlers then
handlers = {}
handlers_for[event_id] = handlers
end
if not next(handlers) then
script.on_event(event_id, dispatch)
end
handlers[handler] = true
end
end
function M.unregister(events, handler)
if type(events) ~= "table" then
events = {events}
end
for _, event_id in ipairs(events) do
-- debug("unregistering for " .. (event_names[event_id] or event_id))
local handlers = handlers_for[event_id]
if handlers then
handlers[handler] = nil
if not next(handlers) then
script.on_event(event_id, nil)
end
end
end
end
function M.register_nth_tick(interval, handler)
local handlers = nth_tick_handlers_for[interval]
if not handlers then
handlers = {}
nth_tick_handlers_for[interval] = handlers
end
if not next(handlers) then
script.on_nth_tick(interval, dispatch_nth_tick)
end
handlers[handler] = true
end
function M.unregister_nth_tick(interval, handler)
local handlers = nth_tick_handlers_for[interval]
if handlers then
handlers[handler] = nil
if not next(handlers) then
script.on_nth_tick(interval, nil)
end
end
end
return M