garbage collected signals for the doors

This commit is contained in:
2024-09-10 17:40:51 -04:00
parent 3180b31928
commit ae4c414928

77
src/shared/GC_Signal.luau Normal file
View File

@@ -0,0 +1,77 @@
--!optimize 2
--!strict
--Garbage collected version of BindableEvents specifically for constantly reused functions
type ClassConstructor = typeof(setmetatable({} :: Constructor_Return_Props, {} :: Impl_Constructor))
type Impl_Constructor = {
__index: Impl_Constructor,
constructor: Constructor_Fun,
--Class functions
Fire: <T...>(self: ClassConstructor, T...) -> (),
Wait: (self: ClassConstructor) -> (),
Connect: (self: ClassConstructor, Callback: <T...>(T...) -> ()) -> Methods,
Once: (self: ClassConstructor, Callback: <T...>(T...) -> ()) -> (),
DisconnectAll: (self: ClassConstructor) -> (),
}
type Constructor_Fun = () -> ClassConstructor
type Constructor_Return_Props = {
__callbacks__: {<T...>(T...) -> ()},
__fired__: boolean
}
export type constructor = ClassConstructor
local Signal = {} :: Impl_Constructor
Signal.__index = Signal
function Signal.constructor()
return setmetatable({
__callbacks__ = {},
__fired__ = false
}, Signal)
end
function Signal:Fire<T...>(...: T...)
self.__fired__ = true
for n: number = 1, #self.__callbacks__ do
self.__callbacks__[n](...)
end
self.__fired__ = false
end
function Signal:Wait()
repeat
task.wait()
until self.__fired__
end
type Methods = {
Disconnect: (self: Methods) -> ()
}
local function SignalConnectedMethods(super: ClassConstructor, cid: number)
local Methods = {} :: Methods
function Methods:Disconnect()
super.__callbacks__[cid] = nil
end
return Methods
end
function Signal:Connect(Callback)
local cid = #self.__callbacks__+1
table.insert(self.__callbacks__, cid, Callback)
return SignalConnectedMethods(self, cid)
end
function Signal:Once(Callback)
task.spawn(function()
self:Wait()
Callback()
end)
end
function Signal:DisconnectAll()
table.clear(self.__callbacks__)
end
return Signal