Problems with functions

for _, button in pairs(CarList) do	-- Go through all the buttons in the table and check if one has been clicked
	button.Activated:Connect(function()	-- button pressed then show info
		-- Bunch of code here that doesn't matter
		InfoScreen.BuyButton.Activated:Connect(function()  -- Player pressed the buy button
			print(button.Name)
		end)
	end)
end

Whenever the player presses a second button then presses buy, both the previous button and the current button name is printed out.
I would imagine I’d have to disconnect the function somewhere, but from what I’ve tried, this doesn’t seem to be the case.

Move the inner button activated function outside of the for loop. You are creating a connection during each iteration for the same button.

This is hard to explain but I’m using the name of the button in the for loop to call a remote event, where the server script refer to models of the same name in server storage.
I can’t do that if button in button.Name is not assigned.

image image

You should be using ipairs I believe if this is not a dictionary. That might not be the problem, but it’s a start.

Also try moving the inner function to the outer function.

I believe you might be over complicating this. You could completely remove the inner connection and store data using local variables. What’s happening is you have a button with multiple connections that are firing all at once.

Try this

local Target = nil
for _, button in pairs(CarList) do
	button.Activated:Connect(function()
		Target = button
	end)
end
InfoScreen.BuyButton.Activated:Connect(function()
	if not Target then			return				end
	print(Target.Name)
end)
1 Like