Should I use connect/disconnect here?

I just want to know if I should/shouldn’t use connect and disconnect here.

I have a module controlling a frame with all of it’s contents, easier to keep organized than making a huge 500 line script.
It returns a function which looks like this:

return function(screenwipe, vars)
	if typeof(screenwipe) ~= "function" then
		error("Argument 1 must be a function.")
	elseif typeof(vars) ~= "table" then
		error("Argument 2 must be a valid table.")
	end
	
	checkExistances(vars)
	
	isOpen = true
	for i, v in pairs(mainFrame:GetDescendants()) do
		if v:IsA("TextButton") then

			v.MouseButton1Click:Connect(function()
				if isOpen and vars.setting.Setting_1Bool then
					vars.clicksound:Play()
				end
			end)

		end
	end
	
	purchasePromptSpawnFrame.MouseButton1Click:Connect(function()
		if isOpen then
			promptPurchase(purchasePromptSpawnFrame)
		end
	end)
	
	BackButton.MouseButton1Click:Connect(function()
		if vars.setting.Setting_1Bool then
			vars.clicksound:Play()
		end
		spawn(screenwipe)
		wait(.5)
		vars.currentFrame.Visible = false
		vars.defaultFrame.Visible = true
		isOpen = false
	end)
	
end

On my button.MouseButton1Click:Connect(function() functions should I be using a connection and disconnect them when the frame is closed?
Will calling this current function each time create multiple connections for the same button?

Thank you to anyone in advance

1 Like

Store all the connections in a table and use for do when you need to disconnect it, also clean the table after that.

local Connections = {}
for _, v in pairs(Connections) do
	v:Disconnect()
end
table.clear(Connections)

thanks.
how should I go about adding connections into it?
(not sure how to insert them with table.insert())

local connections = {}

connection = function()

end)

table.insert(connections,connection)

I believe thats all you gotta do

1 Like

In this scenario, does using button.MouseButton1Click:Connect(function() create multiple connections to the same button, if you don’t disconnect it?

Every time the function is called, it will create an RBXConnection; Imagine that you have a function that connects a button that adds a number

local Number = 0  -- variable outside the main function
Button.MouseButton1Click:Connect(function()
    Number += 1
    print("Current number:", Number) -- 1, 2, 3, etc
end)

if it is not disconnected, 1 will no longer be added: 2, 3, 4, etc. will be added. by the number of times the function has been called

local Number = 0  -- variable outside the main function
Button.MouseButton1Click:Connect(function()
    Number += 1
    print("Current number:", Number) -- 4, 8, 12, etc
end)

In this case, the function has been called 4 times.

1 Like