From ae4c41492837e490d953f3dc4d9127305f52e230 Mon Sep 17 00:00:00 2001 From: unixtensor Date: Tue, 10 Sep 2024 17:40:51 -0400 Subject: [PATCH] garbage collected signals for the doors --- src/shared/GC_Signal.luau | 77 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/shared/GC_Signal.luau diff --git a/src/shared/GC_Signal.luau b/src/shared/GC_Signal.luau new file mode 100644 index 0000000..99edd7c --- /dev/null +++ b/src/shared/GC_Signal.luau @@ -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: (self: ClassConstructor, T...) -> (), + Wait: (self: ClassConstructor) -> (), + Connect: (self: ClassConstructor, Callback: (T...) -> ()) -> Methods, + Once: (self: ClassConstructor, Callback: (T...) -> ()) -> (), + DisconnectAll: (self: ClassConstructor) -> (), +} +type Constructor_Fun = () -> ClassConstructor +type Constructor_Return_Props = { + __callbacks__: {(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...) + 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