Am I able to assign one connection variable to control multiple connections

Title kinda confusing, apologies for that. I’ve also tried looking this up but maybe it’s how my wording is I can’t seem to find anything.

What I’m trying to do is loop a list (this changes a lot of the time) and set a connection variable to the TextButton to avoid a memory leak (not sure if this would still happen if I destroy the instance?)

What I’m mainly asking is if I’m able to do something like this or if I would need to manually make multiple variables for each textbutton.

local buttonConnection

for i, v in next, module do
	local new = example:Clone()
	new.Name.Text = i
	new.Buy.Text = 'Buy ('..v.dollars..')'
	new.Parent = mainFrame.List
	buttonConnection = new.MouseButton1Click:Connect(function()
		Function:InvokeServer('PurchaseWeapon', i, dealer.Parent.Name)
	end)
end

-- the above is inside a loop, code removed for reading purpose

mainFrame.Exit.MouseButton1Click:Connect(function()
	mainFrame.Visible = false
	if buttonConnection then
		buttonConnection:Disconnect()
	end
end)

A more efficient way would be Tables! A great example would be

local connections = {}
for i, v in next, module do
	local new = example:Clone()
	new.Name.Text = i
	new.Buy.Text = 'Buy ('..v.dollars..')'
	ew.Parent = mainFrame.List
	connections[#connections +  1] = new.MouseButton1Click:Connect(function()
		Function:InvokeServer('PurchaseWeapon', i, dealer.Parent.Name)
	end)
end 
connections[#connections + 1] =  mainFrame.Exit.MouseButton1Click:Connect(function()
	mainFrame.Visible = false
end)

--you can disconnect when it isn't needed anymore (ui disappears etc)
for i = 1,#connections do
connections[i]:Disconnect()
end
2 Likes

Thank you alot.
I’d assume I’ll also need to set connections[i] to nil aswell so it doesn’t try to disconnect it again or does the table automatically remove it?

Yes, you would have to remove it, I am guessing you already know how to do that, Just always remember tables can hold Anything.

1 Like

Given that Brandon had a fix solution, I’ll answer the original question for future reference: no, you cannot do this. Each time the loop runs, buttonConnection will be overwritten with a new RBXScriptConnection object until the loop terminates.

Even if you get rid of buttonConnection’s status as an upvalue by moving it into the scope of the loop, that wouldn’t be desirable - the variable would become inaccessible once you exit the scope (writing or executing anything outside the loop).

1 Like

Thank you for the clarification!