update changes
[QuestHelper.git] / Generic / event.lua
blob696aaa7b256109ef9b562484047f1f56650db4a4
1 -- Functions we use here.
2 local create = QuestHelper.create
3 local createCallback = QuestHelper.createCallback
4 local reference = QuestHelper.reference
5 local release = QuestHelper.release
7 -- The metatable for Event objects.
8 local Event = {}
10 function Event:onCreate()
11 rawset(self, "set", create())
12 end
14 function Event:onRelease()
15 local set = rawget(self, "set")
16 for cb in pairs(set) do release(cb) end
17 release(set)
18 end
20 -- Adds a reference to callback to if it hasn't already been added.
21 -- If callback is a function, creates a callback.
22 -- You could probably register another event here as if it were a callback, but I doubt that would be a great idea.
23 -- Returns the passed (or created) callback.
24 function Event:register(callback, ...)
25 local set = rawget(self, "set")
26 if type(callback) == "function" then
27 callback = createCallback(callback, ...)
28 set[callback] = true
29 else
30 if not set[callback] then
31 set[reference(callback)] = true
32 end
33 end
35 return callback
36 end
38 -- Unregisters a callback previously passed to or returned from register.
39 function Event:unregister(callback)
40 local set = rawget(self, "set")
41 assert(set[callback], "Wasn't previously registered.")
42 set[callback] = nil
43 release(callback)
44 end
46 -- Invokes all associated callbacks with passed arguments.
47 function Event:invoke(...)
48 local set = rawget(self, "set")
49 for cb in pairs(set) do cb(...) end
50 end
52 -- Allows event to be invoked as if it were a function.
53 Event.__call = Event.invoke
55 Event.__newindex = function()
56 assert(false, "Shouldn't assign values.")
57 end
59 Event.__index = function(_, key)
60 return rawget(Event, key)
61 end
63 local function createEvent()
64 return create(Event)
65 end
67 QuestHelper.createEvent = createEvent