Hello developers,
I’m coding my own Signal module, and I’m in trouble.
If I try to use the module, it says “Type ‘Signal’ could not be converted into '{ _Connections: {{ Disconnect: () → (), _callback: (…any) → () }} }”.
Here is my module:
-- Signal.lua
--!strict
local Signal = {}
Signal.__index = Signal
type Connection = {
Disconnect: () -> ()
}
type Signal = typeof(setmetatable({}, Signal))
function Signal.New(): Signal
return setmetatable({
_Connections = {}
}, Signal)
end
function Signal:Destroy(): ()
setmetatable(self, nil)
self._Connections = nil
end
function Signal:Connect(callback: (...any) -> ()): Connection
local Connection = {}
Connection._callback = callback
Connection.Disconnect = function()
for index, value in ipairs(self._Connections) do
if value == Connection then
self._Connections[index] = nil
break
end
end
end
table.insert(self._Connections, Connection)
return Connection
end
function Signal:Once(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(): ...any
local CurrentThread = coroutine.running()
self:Once(function(...: any)
coroutine.resume(CurrentThread, ...)
end)
return coroutine.yield()
end
function Signal:Fire(...): ()
for _, Connection in ipairs(self._Connections) do
local callback: () -> () = Connection._callback
if callback then
task.defer(callback, ...)
end
end
end
return Signal