Events stored in arrays, table.Clear, or :Disconnect()

I need to have a large number of events, so I decide to store them in an array because I also need to Disconnect them later. In order to disconnect them, Should I iterate over the array and remove the events using :Disconnect() or should I simply clear the array with table.Clear

for i, event in ipairs(connections) do
    event:Disconnect()
end

or

table.clear(connections)

you’d need to disconnect them manually (for loop) and if needed, clear the table after.

2 Likes

If it’s an array, it’s better to do that:

for index = #connections, 1, -1 do
	connections[index]:Disconnect()
	table.remove(connections, index) -- Remove from the register
end

By doing so, you permanently remove the connections . When you remove an element from an array, such as removing the element at the first index, the element at the second index becomes the first. That’s why you should remove them from the last index to the first to ensure proper table cleanup. It’s crucial to understand that a disconnected connection will always exist unless you manually remove it from the table; otherwise, it will persist. Just for more understanding, you can check if a connection is still active using RbxScriptConnection.Connected as specified in the documentation. So disconnecting them isn’t enough on its own.

Hope I’ve helped you. If you have any questions, don’t hesitate to ask me!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.