Heya, I’m trying to make a table that holds connections and disconnects them when a round ends.
Thing is, I want to use type-checking more, because it makes scripting more manageable to me.
Here is a module script I made:
--!strict
-- Round connections will disconnect when the round ends.
type connections_table_type = {
connections: {RBXScriptConnection},
AddConnection: (self: connections_table_type, connection: RBXScriptConnection) -> (),
DisconnectAll: (self: connections_table_type) -> ()
}
local round_connections: connections_table_type = {
connections = {},
AddConnection = function(self: connections_table_type, connection: RBXScriptConnection)
table.insert(self.connections, connection)
end,
DisconnectAll = function(self: connections_table_type)
for i: number, connection: RBXScriptConnection in self.connections do
connection:Disconnect()
self.connections[i] = nil
end
end,
}
return round_connections
This is how it would look like in practice:
round_connections:AddConnection(game.Players.PlayerAdded:Connect(function(player: Player)
-- do something
end)
round_connections:DisconnectAll()
I could simplify it by doing the following:
table.insert(round_connections, game.Players.PlayerAdded:Connect(function(player: Player)
-- do something
end)
for i: number, connection: RBXScriptConnection in round_connections do
connection:Disconnect()
round_connections[i] = nil
end
Is the module script type checking overkill?
Thanks for reading.
This is one of those situations i would consider overengineering. Like when you create a thorough extensible class that covers many situations, of which you end up only using one.
If you’re arguing about whether or not you need an abstraction layer for something simple like storing and managing connections, it’s truly up to you since you’re maintaining the codebase.
Personally, I would keep the abstraction, just keep in mind the typechecker can infer the return types of functions if you define them separately, and also infer the type of the module when its returned, so making a global type is somewhat redundant for my taste
Thanks, just had a feeling like it was too much. I like type checking because it makes code feel more solid but sometimes it can overcomplicate things for me.
I’ll go with the simpler approach of using one {RBXScriptSignal} type table.
if you would like my opinion of how i would do it, here’s a snippet:
--!strict
local connections: {RBXScriptConnection} = {}
function addConnection(cnc: RBXScriptConnection)
table.insert(connections, cnc)
end
function disconnectAll()
for _, cnc in pairs(connections) do
cnc:Disconnect()
end
table.clear(connections)
end
return {
addConnection = addConnection,
disconnectAll = disconnectAll
}