Connecting a button clicked event causes an infinite loop

Hello,
I’m trying to make a whitelist system in the my game similar to lumber tycoon, and I’m trying to do that by having a players list where you can click a player’s name to whitelist them, and I know there are simple ways to do it but I want to do it this way to learn.
here is how I do it: adding a player to the whitelist deletes the player’s name from the player list, and then it appears in the whitelist, and it is done by having a function that goes over all the whitelisted players and creates the whitelist GUI where each player’s name is a button, thus after the creation of the buttons I connect each button to the function that removes the player from the whitelist which also goes over the whitelisted players and recreates the list, so what I expect to happen is that after a player is added all the buttons are connected to a function that recreates the buttons, but because the button of removing a player from the whitelist hasn’t been pressed yet it should stop there, but what ends up happening is that it enters an infinite loop as if the event of removing a player from the list has been fired.

this is the part of the function that recreates the whitelist

for i, v in pairs (players) do
		local button = Instance.new("TextButton", addedPlayerList)
		button.Size = UDim2.fromScale(1, baseY)
		button.Position = UDim2.fromScale(0, currentYPos)
		currentYPos += baseY
		button.Text = v.Name
		button.MouseButton1Click:Connect(removePlayerFromAddedList(state, game.Players[v.Name]))
end

and this is removePlayerFromADdedList is the connected to the buttons in the whitelist:

function removePlayerFromAddedList(state, playerToRemove)
	print("bb")
	if player:FindFirstChild(playerToRemove.Name) then
		player[playerToRemove.Name]:Destroy()
	end
	makePlayerList(state)
	makeAddedPlayerList(state)
end

and this is the outpost once it tries to create the player list (the same problem happens whether I’m trying to create the player list or the whitelist that is called in the called AddedPlayerList)

Your functions are looping, remove one of these calls. makeAddedPlayerList probably shouldn’t remove players from added list right?

removePlayerFromAddedList → makePlayerList → addPlayerToAddedList → makeAddedPlayerList → removePlayerFromAddedList → repeat…

1 Like

I see that but makePlayerList doesn’t call addPlayerToAddedList, it only connects it to the button, thus addPlayerToAddedList is called when the newly created button is pressed, so it should be removePlayerFromAddedList → makePlayerList → wait for button press → addPlayerToAddedList → makeAddedPlayerList …

1 Like

Connections do not show in the traces. There is a call to addPlayerToAddedList somewhere in that function.

1 Like