well it appears to function
[QuestHelper.git] / Generic / callback.lua
blobcd7152298f2ba37b3eaf36852136daf9251a0055
1 local create = QuestHelper.create
2 local release = QuestHelper.release
3 local erase = table.remove
4 local append = QuestHelper.append
6 -- The metatable for Callback objects.
7 local Callback = {}
9 -- Initiates a callback that will invoke func with some arguments, plus any additional arguments
10 -- passed at the time the callback is invoked.
11 function Callback:onCreate(func, ...)
12 rawset(self, 0, func)
13 rawset(self, "r", 0)
14 append(self, ...)
15 end
17 function Callback:onRelease()
18 for i = -1, rawget(self, "r"), -1 do release(rawget(self, i)) end
19 end
21 local function cb_release(cb, tbl, ...)
22 if tbl then
23 assert(type(tbl) == "table", "Can only release tables.")
24 local r = rawget(cb, "r")
25 r = r - 1
26 rawset(cb, r, tbl)
27 rawset(cb, "r", r)
28 cb_release(cb, ...)
29 end
30 end
32 -- The callback doesn't do any special book keeping with the function's arguments.
33 -- If you would like any of them to be released when the callback is, pass them
34 -- to this function.
35 Callback.release = cb_release
37 local temp = {}
39 -- Invokes the callback, appending any passed arguments to those assigned when the callback was created.
40 function Callback:invoke(...)
41 while erase(temp) do end
42 append(temp, unpack(self))
43 append(temp, ...)
44 return rawget(self, 0)(unpack(temp))
45 end
47 -- Allows you to use a callback as if it were a function.
48 Callback.__call = Callback.invoke
50 Callback.__newindex = function()
51 assert(false, "Shouldn't assign values.")
52 end
54 Callback.__index = function(_, key)
55 return rawget(Callback, key)
56 end
58 local function createCallback(...)
59 return create(Callback, ...)
60 end
62 QuestHelper.createCallback = createCallback