Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Last active November 8, 2022 15:56
Show Gist options
  • Save cxmeel/fce01f8abb73a6a73c9228ba969e835e to your computer and use it in GitHub Desktop.
Save cxmeel/fce01f8abb73a6a73c9228ba969e835e to your computer and use it in GitHub Desktop.
Recreation of Roblox RBXScriptSignals in pure Lua
--[[
RawSignal by csqrl (ClockworkSquirrel)
Version: 0.0.2
License: MIT
Originally uploaded to Dcoder.
Documentation:
Signal:
Methods:
Signal.new(): RawSignal
RawSignal:
Methods:
RawSignal:Connect(Callback: function): DisconnectionTable
RawSignal:Fire(...): void
RawSignal:Destroy(): void
DisconnectionTable:
Methods:
DisconnectionTable:Disconnect(): void
--]]
local Signal = {}
Signal.__index = Signal
function Signal.new()
local self = setmetatable({}, Signal)
self.__callbackInt = 0
self.__callbacks = {}
return self
end
function Signal:Connect(Callback)
if self._destroyed then
error("Signal has been destroyed", 2)
end
local this = self
this.__callbackInt = this.__callbackInt + 1
local CallbackId = tostring(this.__callbackInt)
this.__callbacks[CallbackId] = Callback
return {
Disconnect = function()
this.__callbacks[CallbackId] = nil
end
}
end
function Signal:Fire(...)
if self._destroyed then
error("Signal has been destroyed", 2)
end
for _, callback in next, self.__callbacks do
coroutine.wrap(callback)(...)
end
end
function Signal:Destroy()
self._destroyed = true
for key, _ in next, self.__callbacks do
self.__callbacks[key] = nil
end
for key, _ in pairs(self) do
self[key] = nil
end
end
return Signal
MIT License
Copyright (c) 2020 csqrl (a.k.a. ClockworkSquirrel)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software without modification.
THE SOFTWARE IS PROVIDED "AS IS" BY CSQRL, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR
(CSQRL), CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment