How would a variable behave if it equated from one function to another?

This might be a little hard to explain given the title, (or it might be a silly question to ask), but it’s something that is kind of integral to how my code works.

For my round system/gamemodes to work, I have a variable that constantly references different functions, so at the end of each round, my script can easily disconnect it in the end.

The thing about the variable is that it is going to reference one function, and I’ll show a snippet here:

			roundConnection = Funcs.CapitalFirstPhase(roundConnection) -- begin phase 1
			game.Workspace:SetAttribute("roundChooseTimer", 45)
			Funcs.SpawnTrees(Trees)
		end
    end

After the first phase of the round is complete, the variable roundConnection will now equate to this:

		wait(5)
		roundConnection = Funcs.CapitalLastPhase(RedTeam, BlueTeam, roundConnection) --begin phase 2

What would happen to the function that was loaded by this variable beforehand? Would it continue running, even though roundConnection now equates to a new variable? I wanted to know if this was okay so I can prevent any memory leaks.

Yeah, even if you lose a reference to your connection, the connection will be active and will still run so you should probably have a variable in the scope of both functions (or a module, see Quenty’s maid class) to not create a bunch of connections (although do note that destroying the instance whose connection is active will disconnect the connection so if you’re destroying that instance, don’t worry about disconnecting it).

local roundConnection

local function func1()
    if roundConnection then
        roundConnection:Disconnect()
    end
    roundConnection = workspace.DescendantAdded:Connect(function() end)
end
local function func2()
    if roundConnection then
        roundConnection:Disconnect()
    end
    roundConnection = workspace.DescendantAdded:Connect(function() end)
end
func1()
task.wait(5)
func2()
1 Like

Thanks for the help, it’s one step closer to learn how functions behave

1 Like