-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSignal.luau
75 lines (63 loc) · 1.63 KB
/
Signal.luau
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
--!strict
--!native
--!optimize 2
--// Paficent \\-
--// Types
type SignalConnection = {
Disconnect: () -> ()
}
--// Module Declaration
local Signal = {}
Signal.__index = Signal
--// Constructor
function Signal.new()
return setmetatable({
_connections = {} :: {(...any) -> ()},
}, Signal)
end
-- Connects a callback function to the signal
function Signal:Connect(callback: (...any) -> ()): SignalConnection
table.insert(self._connections, callback)
local connection = {
Disconnect = function()
for i, conn in ipairs(self._connections) do
if conn == callback then
table.remove(self._connections, i)
break
end
end
end
}
return connection :: SignalConnection
end
-- Connects a callback that will be called only once
function Signal:Once(callback: (...any) -> ())
local connection
connection = self:Connect(function(...)
callback(...)
connection.Disconnect()
end)
return connection
end
-- Waits until the signal is fired and returns the arguments passed to the signal
function Signal:Wait(): ...any
local waiting = true
local result
local connection
connection = self:Connect(function(...)
result = {...}
waiting = false
connection.Disconnect()
end)
while waiting do
task.wait()
end
return unpack(result)
end
-- Fires the signal, calling all connected callbacks with the provided arguments
function Signal:Fire(...: any)
for _, callback in ipairs(self._connections) do
callback(...)
end
end
return Signal