Created
October 13, 2018 23:01
-
-
Save tiffany352/449b34fd4401f9be9f626d1871edeca9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Connection = {} | |
Connection.__index = Connection | |
function Connection.new(signal, func) | |
local self = { | |
signal = signal, | |
func = func, | |
} | |
setmetatable(self, Connection) | |
return self | |
end | |
function Connection:disconnect() | |
if self.signal then | |
self.signal.connections[self.func] = nil | |
self.signal = nil | |
self.func = nil | |
end | |
end | |
local Signal = {} | |
Signal.__index = Signal | |
function Signal.new() | |
local self = { | |
connections = {}, | |
} | |
setmetatable(self, Signal) | |
return self | |
end | |
function Signal:fire(...) | |
for func,_ in pairs(self.connections) do | |
func(...) | |
end | |
end | |
function Signal:connect(func) | |
self.connections[func] = true | |
return Connection.new(self, func) | |
end | |
function Signal:wait() | |
local thread = coroutine.running() | |
-- If you want to silence errors, then use coroutine.resume instead | |
local conn = self:connect(coroutine.wrap(thread)) | |
coroutine.yield() | |
conn:disconnect() | |
end | |
return Signal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment