-- Signal.lua
--!strict
local Signal = {}
Signal.__index = Signal
local Connection = {}
Connection.__index = Connection
type Connection = typeof(setmetatable({} :: {
signal: Signal,
_callback: any
}, Connection))
type Signal = typeof(setmetatable({} :: {
_Connections: {Connection}
}, Signal))
function Connection.New(signal: Signal, callback: (...any) -> ()): Connection
local _Connection = {
signal = signal,
_callback = callback
}
setmetatable(_Connection, Connection)
table.insert(signal._Connections, _Connection)
return _Connection
end
function Connection.Disconnect(self: Connection): ()
local connections = self.signal._Connections
for index, value in ipairs(connections) do
if value == self then
table.remove(connections, index)
break
end
end
end
function Signal.New(): Signal
return setmetatable({
_Connections = {}
}, Signal) :: any
end
function Signal.Destroy(self: Signal): ()
setmetatable(self :: any, nil)
table.clear(self._Connections)
end
function Signal.Connect(self: Signal, callback: (...any) -> ()): Connection
return Connection.New(self, callback)
end
function Signal.Once(self: Signal, callback: (...any) -> ()): Connection
local Connection: Connection
local HasFired: boolean = false
Connection = self:Connect(function(...: any)
if not HasFired then
HasFired = true
Connection:Disconnect()
task.defer(callback, ...)
end
end)
return Connection
end
function Signal.Wait(self: Signal): ...any
local CurrentThread = coroutine.running()
self:Once(function(...: any)
coroutine.resume(CurrentThread, ...)
end)
return coroutine.yield()
end
function Signal.Fire(self: Signal, ...: any): ()
for _, Connection in ipairs(table.clone(self._Connections)) do
local callback: (...any) -> () = Connection._callback
if callback then
task.defer(callback, ...)
end
end
end
function Signal.GetConnections(self: Signal): {Connection}
return table.clone(self._Connections)
end
return Signal
Any feedback would be appreciated!