Skip to content
This repository has been archived by the owner on Jul 28, 2022. It is now read-only.

Commit

Permalink
Merge pull request #209 from Sleitnick/signal-improvements
Browse files Browse the repository at this point in the history
Signal improvements
  • Loading branch information
Sleitnick authored Mar 15, 2021
2 parents 187d14a + 30ec5b9 commit 5aef27a
Showing 1 changed file with 36 additions and 6 deletions.
42 changes: 36 additions & 6 deletions src/ReplicatedStorage/Aero/Shared/Signal.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@

--[[
signal = Signal.new()
signal = Signal.new([maid: Maid])
signal = Signal.Proxy(rbxSignal: RBXScriptSignal [, maid: Maid])
signal:Fire(...)
signal:Wait()
signal:WaitPromise()
signal:Destroy()
signal:DisconnectAll()
connection = signal:Connect(functionHandler)
connection = signal:Connect((...) -> void)
connection.Connected
connection:Disconnect()
Expand Down Expand Up @@ -66,23 +67,51 @@ local Signal = {}
Signal.__index = Signal


function Signal.new()
function Signal.new(maid)
local self = setmetatable({
_bindable = Instance.new("BindableEvent");
_connections = {};
_args = {};
_threads = 0;
_id = 0;
}, Signal)
if (maid) then
maid:GiveTask(self)
end
return self
end


function Signal.Proxy(rbxScriptSignal, maid)
assert(typeof(rbxScriptSignal) == "RBXScriptSignal", "Argument #1 must be of type RBXScriptSignal")
local signal = Signal.new(maid)
signal:_setProxy(rbxScriptSignal)
return signal
end


function Signal.Is(obj)
return (type(obj) == "table" and getmetatable(obj) == Signal)
end


function Signal:_setProxy(rbxScriptSignal)
assert(typeof(rbxScriptSignal) == "RBXScriptSignal", "Argument #1 must be of type RBXScriptSignal")
self:_clearProxy()
self._proxyHandle = rbxScriptSignal:Connect(function(...)
self:Fire(...)
end)
end


function Signal:_clearProxy()
if (self._proxyHandle) then
self._proxyHandle:Disconnect()
self._proxyHandle = nil
end
end


function Signal:Fire(...)
local id = self._id
self._id = self._id + 1
Expand All @@ -93,10 +122,10 @@ end


function Signal:Wait()
self._threads = self._threads + 1
self._threads += 1
local id = self._bindable.Event:Wait()
local args = self._args[id]
args[1] = args[1] - 1
args[1] -= 1
if (args[1] <= 0) then
self._args[id] = nil
end
Expand All @@ -114,7 +143,7 @@ end
function Signal:Connect(handler)
local connection = Connection.new(self, self._bindable.Event:Connect(function(id)
local args = self._args[id]
args[1] = args[1] - 1
args[1] -= 1
if (args[1] <= 0) then
self._args[id] = nil
end
Expand All @@ -138,6 +167,7 @@ end

function Signal:Destroy()
self:DisconnectAll()
self:_clearProxy()
self._bindable:Destroy()
end

Expand Down

0 comments on commit 5aef27a

Please sign in to comment.