--!strict --[[ Signal — a tiny, typed event object for Luau. SKLOP Studio · https://sklop.vercel.app · MIT License (free to use in any project) USAGE local Signal = require(path.to.Signal) local coinsChanged = Signal.new() :: Signal.Signal local connection = coinsChanged:Connect(function(amount) print("Coins:", amount) end) coinsChanged:Fire(250) connection:Disconnect() coinsChanged:Once(function(amount) print("first change only", amount) end) local amount = coinsChanged:Wait() -- yields until the next :Fire NOTES • Each handler runs in its own thread (task.spawn), so one erroring handler never stops the others. • Connecting or disconnecting while the signal is firing is safe. ]] export type Connection = { Connected: boolean, Disconnect: (self: Connection) -> (), } export type Signal = { Connect: (self: Signal, handler: (T...) -> ()) -> Connection, Once: (self: Signal, handler: (T...) -> ()) -> Connection, Wait: (self: Signal) -> T..., Fire: (self: Signal, T...) -> (), DisconnectAll: (self: Signal) -> (), Destroy: (self: Signal) -> (), } type Handler = { fn: (...any) -> (), connected: boolean, } type SignalState = { _handlers: { Handler }, } local SignalClass = {} SignalClass.__index = SignalClass local Signal = {} --- Creates a new signal. function Signal.new(): Signal local state: SignalState = { _handlers = {} } return (setmetatable(state, SignalClass) :: any) :: Signal end function SignalClass.Connect(self: SignalState, fn: (...any) -> ()): Connection assert(type(fn) == "function", "Signal:Connect expects a function") local handler: Handler = { fn = fn, connected = true } table.insert(self._handlers, handler) local connection: Connection = { Connected = true, Disconnect = function(conn: Connection) if not conn.Connected then return end conn.Connected = false handler.connected = false local index = table.find(self._handlers, handler) if index then table.remove(self._handlers, index) end end, } return connection end function SignalClass.Once(self: SignalState, fn: (...any) -> ()): Connection local connection: Connection connection = SignalClass.Connect(self, function(...) connection:Disconnect() fn(...) end) return connection end function SignalClass.Wait(self: SignalState): ...any local thread = coroutine.running() SignalClass.Once(self, function(...) task.spawn(thread, ...) end) return coroutine.yield() end function SignalClass.Fire(self: SignalState, ...: any) -- Iterate over a snapshot so handlers may connect/disconnect while firing. for _, handler in table.clone(self._handlers) do if handler.connected then task.spawn(handler.fn, ...) end end end function SignalClass.DisconnectAll(self: SignalState) for _, handler in self._handlers do handler.connected = false end table.clear(self._handlers) end function SignalClass.Destroy(self: SignalState) SignalClass.DisconnectAll(self) end return Signal