Organizing Connections!?!?
Currently I am organizing a Pathfinding system which utilizes the RBXScriptConnections of Path.Blocked
, Path.Unblocked
, and vice versa.
For organizational purposes I have created a simple OOP module for storing Connections.
-- Declarations
local ConnectionStorage = {}
local ConnectionFunctions = {}
ConnectionFunctions.__index = ConnectionFunctions
-- Functions
function ConnectionStorage.new()
local NewConnectionStorage = setmetatable({}, ConnectionFunctions)
return NewConnectionStorage
end
function ConnectionFunctions:AddConnection(Key :string, Connection : RBXScriptConnection) : nil
if not (Key and type(Key) == "string") then
error(`Key needs to be string. Got {Key}.`)
end
if not (Connection and typeof(Connection) == "RBXScriptConnection") then
error(`Connection needs to be RBXScriptConnection. Got: {Connection}.`)
end
local FoundConnection = self[Key]
if FoundConnection and typeof(FoundConnection) == "RBXScriptConnection" then
FoundConnection:Disconnect()
self[Key] = nil
end
self[Key] = Connection
return nil
end
function ConnectionFunctions:GetConnection(Key :string) : nil
if not (Key and type(Key) == "string") then
error(`Key needs to be string. Got {Key}.`)
end
local FoundConnection = self[Key]
if FoundConnection and typeof(FoundConnection) == "RBXScriptConnection" then
return FoundConnection
end
warn(`No Connection under Key of {Key}.`)
return nil
end
function ConnectionFunctions:DiscardConnection(Key :string) : nil
if not (Key and type(Key) == "string") then
error(`Key needs to be string. Got {Key}.`)
end
local FoundConnection = self[Key]
if FoundConnection and typeof(FoundConnection) == "RBXScriptConnection" then
FoundConnection:Disconnect()
self[Key] = nil
else
warn(`No Connection under Key of {Key}.`)
end
return nil
end
function ConnectionFunctions:DiscardAllConnections() : nil
for Key, Connection : RBXScriptConnection in self do
if not (Connection and typeof(Connection) == "RBXScriptConnection") then
continue
end
Connection:Disconnect()
self[Key] = nil
end
return nil
end
return ConnectionStorage
Blocked use-case:
PathfindingConnections:AddConnection("BlockedConnection", ZombiePath.Blocked:Connect(function(BlockedWaypointId)
if not (BlockedWaypointId >= WaypointId) then
return nil
end
PathfindingConnections:DiscardAllConnections()
CalculatePath(Goal)
return nil
end))