Would this code leak the connections?

I have tested a few ways of disconnecting all of my connections through a single function and I just would like to know if this code would not leak the connection. The problem with this is after I call the ‘DestroyConnection’ function the Connections table still prints 2, and I’m not too sure why it does. FYI this is not my actual in-game script.

local Connections = {}

local function DestroyConnections()
	for i, v in pairs(Connections) do
		v:Disconnect()
		v = nil
	end
end


do 
	local Connection = workspace.Part.Touched:Connect(function() print('PartTouched') end)
	table.insert(Connections,Connection)
	print(#Connections) -- Prints 1
end


do
	local Connection2 = workspace.PART.Touched:Connect(function() print('PART touched') end)
	table.insert(Connections,Connection2)
	print(#Connections) -- Prints 2
end

wait(10)
print('destroying connections')
DestroyConnections()

print(#Connections) -- Still prints 2 ... ?

It actually did disconnect your connection. You just have to set the connection table to {}.

v is a local variable so setting it to nil doesn’t remove the connection from the table. You can do
Connections[i] = nil to remove it from the table. However instead of doing that I would recommend you call table.clear(Connections) to efficiently clear the table.
Also what do you mean by ‘leaking’ the connections? Like memory leak?

1 Like
local function DestroyConnections()
	for i, v in pairs(Connections) do
		v:Disconnect()
		v = nil
	end
end

v is a variable, setting it to nil won’t actually remove it from the table.

What you can do is set the keys to nil when iterating but that is unnecessary.

local function DestroyConnections()
	for i, v in pairs(Connections) do
		v:Disconnect()
		Connections[i] = nil
	end
end

It doesn’t matter if the keys in Connections are nil, just ensure that the connection is disconnected. Also, since the function passed to the touched event doesn’t do anything expensive, it won’t cause a memory leak.

3 Likes

So It would be fine If I used this script for Disconnecting many Remote Events in one script?

Yes I do mean a memory leak. My game uses a lot of events and ‘apparently’ events are the easiest to cause a memory leak if not disconnected. So I just wanted to make sure I could effectively disconnect my connections.