-
Notifications
You must be signed in to change notification settings - Fork 8
/
EventLib.lua
307 lines (264 loc) · 8.74 KB
/
EventLib.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
-- EventLib - An event library in pure lua (uses standard coroutine library)
-- License: WTFPL
-- Author: Elijah Frederickson
-- Version: 1.0
-- Copyright (C) 2012 LoDC
--
-- Description:
-- ROBLOX has an event library in its RbxUtility library, but it isn't pure Lua.
-- It originally used a BoolValue but now uses BindableEvent. I wanted to write
-- it in pure Lua, so here it is. It also contains some new features.
--
--
-- API:
--
-- EventLib
-- new([name])
-- aliases: CreateEvent
-- returns: the event, with a metatable __index for the EventLib table
-- Connect(event, func)
-- aliases: connect
-- returns: a Connection
-- Disconnect(event, [func])
-- aliases: disconnect
-- returns: the index of [func]
-- notes: if [func] is nil, it removes all connections
-- DisconnectAll(event)
-- notes: calls Disconnect()
-- Fire(event, ... <args>)
-- aliases: Simulate, fire, simply calling the table
-- notes: resumes all :wait() first
-- Wait(event)
-- aliases: wait
-- returns: the Fire() arguments
-- notes: blocks the thread until Fire() is called
-- ConnectionCount(event)
-- returns: the number of current connections
-- Spawn(func)
-- aliases: spawn
-- returns: the result of func
-- notes: runs func in a separate coroutine/thread
-- Destroy(event)
-- aliases: destroy, Remove, remove
-- notes: renders the event completely useless
-- WaitForCompletion(event)
-- notes: blocks current thread until the current event Fire() is done
-- If a connected function calls WaitForCompletion, it will hang forever
-- IsWaiting(event)
-- returns: if the event has any waiters
-- WaitForWaiters(event)
-- notes: waits for all waiters to finish. Called in Fire() to make sure that all
-- the waiting threads are done before settings self.args to nil
--
-- Event
-- [All EventLib functions]
-- EventName
-- Property, defaults to "<Unknown Event>"
-- <Private fields>
-- handlers, waiter, args, waiters, executing,
--
-- Connection
-- Disconnect
-- aliases: disconnect
-- returns: the result of [Event].Disconnect
--
-- Basic usage (there are some tests on the bottom):
-- local EventLib = require'EventLib'
-- For ROBLOX use: repeat wait() until _G.EventLib local EventLib = _G.EventLib
--
-- local event = EventLib:new()
-- local con = event:Connect(function(...) print(...) end)
-- event:Fire("test") --> 'test' is print'ed
-- con:disconnect()
-- event:Fire("test") --> nothing happens: no connections
--
-- Supported versions/implementations of Lua:
-- Lua 5.1, 5.2
-- SharpLua 2
-- MetaLua
-- RbxLua (automatically registers if it detects ROBLOX)
--[[
Issues:
- None
Todo:
Changelog:
v1.1
- Added metamethod for __call on events to trigger the Fire() method
- Formatted asserts away from the rest of the function
- Added a pseudo-wait function for environments that don't already have one
- Improved Disconnect() to accept the tables returned by Connect()
v1.0
- Initial version
]]
local _M = { }
_M._VERSION = "1.1"
_M._M = _M
_M._AUTHOR = "Elijah Frederickson"
_M._COPYRIGHT = "Copyright (C) 2012-2015 Elijah Frederickson"
local unpack = unpack or table.unpack
local function spawn(f)
return coroutine.resume(coroutine.create(function()
f()
end))
end
_M.Spawn = spawn
_M.spawn = spawn
local function _wait(...)
if wait then
return wait(...)
end
local waitTime = ({ ... })[1] or 0
local t1 = os.time()
while true do
local t2 = os.time()
if t2 - t1 >= waitTime then
return t2 - t1
end
end
end
_M._wait = _wait
function _M:new(name)
assert(self ~= nil and type(self) == "table" and self == _M, "Invalid EventLib table (make sure you're using ':' not '.')")
local s = { }
s.handlers = { }
s.waiter = false
s.args = nil
s.waiters = 0
s.EventName = name or "<Unknown Event>"
s.executing = false
return setmetatable(s, { __index = self, __call = function(t, ...) return t:fire(...) end })
end
_M.CreateEvent = _M.new
function _M:Connect(handler)
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
assert(type(handler) == "function", "Invalid handler. Expected function got " .. type(handler))
assert(self.handlers, "Invalid Event")
table.insert(self.handlers, handler)
local t = { }
t.func = handler
t.Disconnect = function()
return self:Disconnect(handler)
end
t.disconnect = t.Disconnect
return t
end
_M.connect = _M.Connect
function _M:Disconnect(handler)
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
assert(type(handler) == "function" or type(handler) == "nil" or type(handler) == "table", "Invalid handler. Expected function, table, or nil, got " .. type(handler))
if not handler then
self.handlers = { }
else
for k, v in pairs(self.handlers) do
if v == (type(handler) == "table" and handler.func or handler) then
self.handlers[k] = nil
return k
end
end
end
end
_M.disconnect = _M.Disconnect
function _M:DisconnectAll()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
return self:Disconnect()
end
function _M:Fire(...)
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
assert(self.handlers, "Invalid Event: No handler table")
self.args = { ... }
self.executing = true
self.waiter = false
local i = 0
for k, v in pairs(self.handlers) do
i = i + 1
spawn(function()
v(unpack(self.args))
i = i - 1
if i == 0 then self.executing = false end
end)
end
self:WaitForWaiters()
self.args = nil
--self.executing = false
end
_M.Simulate = _M.Fire
_M.fire = _M.Fire
function _M:Wait()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
self.waiter = true
self.waiters = self.waiters + 1
while self.waiter or not self.args do self._wait(1) end
self.waiters = self.waiters - 1
return unpack(self.args)
end
_M.wait = _M.Wait
function _M:ConnectionCount()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
return #self.handlers
end
function _M:Destroy()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
self:DisconnectAll()
for k, v in pairs(self) do
self[k] = nil
end
setmetatable(self, { })
end
_M.destroy = _M.Destroy
_M.Remove = _M.Destroy
_M.remove = _M.Destroy
function _M:WaitForCompletion()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
while self.executing do self._wait(1) end
while self.waiters > 0 do self._wait(1) end
end
function _M:IsWaiting()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
return self.waiter or self.waiters > 0
end
function _M:WaitForWaiters()
assert(self ~= nil and type(self) == "table", "Invalid Event (make sure you're using ':' not '.')")
while self.waiters > 0 do self._wait(1) end
end
-- Tests
if false then
local e = _M:new("test")
local f = function(...) print("| Fired!", ...) end
local e2 = e:connect(f)
e:fire("arg1", 5, { })
-- Would work in a ROBLOX Script, but not on Lua 5.1...
if script ~= nil and failhorribly then
spawn(function() print("Wait() results", e:wait()) print"|- done waiting!" end)
end
e:fire(nil, "x")
print("Disconnected events index:", e:disconnect(f))
print("Couldn't disconnect an already disconnected handler?", e2:disconnect()==nil)
print("Connections:", e:ConnectionCount())
assert(e:ConnectionCount() == 0 and e:ConnectionCount() == #e.handlers)
e:connect(f)
e:connect(function() print"Throwing error... " error("...") end)
e:fire("Testing throwing an error...")
e:disconnect()
e:Simulate()
f("plain function call")
assert(e:ConnectionCount() == 0)
if wait then
e:connect(function() wait(2, true) print'fired after waiting' end)
e:Fire()
e:WaitForCompletion()
print'Done!'
end
local failhorribly = false
if failhorribly then -- causes an eternal loop in the WaitForCompletion call
e:connect(function() e:WaitForCompletion() print'done with connected function' end)
e:Fire()
print'done'
end
e:Destroy()
assert(not e.EventName and not e.Fire and not e.Connect)
end
if shared and Instance then -- ROBLOX support
shared.EventLib = _M
_G.EventLib = _M
end
return _M