Help with disconnecting function

So I recently found out about data leaks and stuff. I was working on a script for my game that removes a player from a table if they die. It has nested connections. So, my question here is that if i remove the connection that comes first, will the connection inside that connection also be disconnected or will I have to disconnect both of them?

Here, if i disconnect the “game:GetService(‘Players’).PlayerAdded:Connect(function(player)” function will the “player.CharacterAdded:Connect(function(character)” function and the “character:WaitForChild(“Humanoid”).Died:Connect(function()” function also be disconnected?

game:GetService('Players').PlayerAdded:Connect(function(player)
		player.CharacterAdded:Connect(function(character)
			character:WaitForChild("Humanoid").Died:Connect(function()
				if table.find(play, player.Name) then
					local pos = table.find(play, player.Name)
					table.remove(play, pos)
				end
			end)
		end)
	end)

No, you need to disconnect them both.

1 Like

Will it be something like this or is there a better way to go about it?

connection2 = game:GetService('Players').PlayerAdded:Connect(function(player)
		connection3 = player.CharacterAdded:Connect(function(character)
			connection4 = character:WaitForChild("Humanoid").Died:Connect(function()
				if table.find(play, player.Name) then
					local pos = table.find(play, player.Name)
					table.remove(play, pos)
				end
				if not Alive then
					connection4:Disconnect()
				end
			end)
			if not Alive then
				connection3:Disconnect()
			end
		end)
		if not Alive then
			connection2:Disconnect()
		end
	end)

Why do you need to disconnect the player added?
Its better if you store them as a dictionary, using the player userid as the key:

local playerConnections = {}

game:GetService('Players').PlayerAdded:Connect(function(player)
	local userId = player.UserId

	playerConnections[userId] = {}
	playerConnections[userId].CharacterAdded = player.CharacterAdded:Connect(function(character))
		if (typeof(playerConnections[userId].HumanoidDied) == "RBXScriptConnection") then
			playerConnections[userId].HumanoidDied:Disconnect()
		end

		playerConnections[userId].HumanoidDied = character:WaitForChild("Humanoid").Died:Connect(function())
			local index = table.find(play, player.Name)

			if (not index) then return end
				
			table.remove(play, index)
		end)
	end)
end)

I don’t know about dictionaries and stuff as I started learning to program only recently.
Thanks by the way.

I changed the script by the way.

1 Like

Keep in mind those table entries will need to be removed when their respective players leave the game.

local Game = game
local Players = Game:GetService("Players")

local Table = {}

local function OnPlayerRemoving(Player)
	Table[Player.UserId] = nil
end

Players.PlayerRemoving:Connect(OnPlayerRemoving)