How do nested functions with :Connect() work?


There are multiple functions inside :Connect(), how does this work? Does the function just wait for the event? Is this a bad thing to do? What happens if you replace game.Players.PlayerAdded:Connect() with something that can happen more than once before the second event even fires like character.Humanoid.Seated:Connect()?

1 Like

It is absolutely fine to do that. The functions connected to events do “wait” for the events to take place, that is for the event signals to be fired, though not in the sense of yielding, they are simply called whenever the event takes place.

Imagine you stored functions (references to them that is) in a table, and then doing task.spawn() for all of them whenever a certain condition is met. Not saying that’s exactly it, but it’s a good way to think about it.

If you replace PlayerAdded with something that might happen multiple times, then the connected function will be called multiple times, and you’ll be making the CharacterAdded connection multiple times and so on, which you don’t want.

If your goal is the Seated event then this is the right way to go about it, just make sure to also process the Players that are already added (you have to do this for Studio testing) and check if the character was already added, check if the Humanoid is already seated, and so on. Some other things as well, but I’ll stick to what you asked about.

1 Like

What do you mean by proccesing if the players are already added and what is “Studio testing”? The more you tell me the better, I’m pretty new to scripting.

Functions that are connected to an event using :Connect or :Once or :ConnectParallel will only run if the event is triggered so the safety of nesting connections depends on the event’s context and how frequently it’s triggered. As an example, a common beginner’s mistake is doing this:

local tool = script.Parent

tool.Equipped:Connect(function(mouse)
	mouse.Button1Down:Connect(function()
		
	end)
end)

which will cause a memory leak since a new connection is created whenever the Tool is equipped so in this situation a method one can use to solve it is by doing this:

local tool = script.Parent

local connection

tool.Equipped:Connect(function(mouse)
	connection = mouse.Button1Down:Connect(function()
		
	end)
end)

tool.Unequipped:Connect(function()
	if connection then
		connection:Disconnect()
		connection = nil
	end
end)

This will disconnect the connection when the Tool is unequipped preventing the memory leak from occuring

1 Like

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