Code runs too fast for its own good

Here are my functions:

Functions
local function SelectButton(button)

	button.BackgroundColor3 = Color3.fromRGB(200, 255, 200)
	button:SetAttribute("selected", true)
	
	print("SelectButton", button)

end

local function DeselectButton(button)

	button.BackgroundColor3 = Color3.fromRGB(255, 255, 255)
	button:SetAttribute("selected", false)
	
	print("DeselectButton", button, button:GetAttribute("selected"))

end

local function SelectToolBarButton(button)

	if button == nil then
		return
	end

	currentToolBarButton = button

	SelectButton(button)

end

local function DeselectToolBarButton(button)

	if button == nil then
		return
	end

	if currentToolBarButton ~= nil and previousToolBarButton ~= nil and previousToolBarButton ~= currentToolBarButton then
		doublePreviousToolBarButton = previousToolBarButton
	end

	previousToolBarButton = currentToolBarButton
	currentToolBarButton = nil

	DeselectButton(button)

end

local function ReselectCurrentToolBarButton()
	
	print("ReselectCurrentToolBarButton")

	DeselectToolBarButton(currentToolBarButton)
	SelectToolBarButton(previousToolBarButton)
	
	print("ReselectCurrentToolBarButton")

end

And here’s the code that’s the issue:


Now this is what it prints:

My theory is:
By the time it detects that the attribute got changed, the attribute already got changed again, so the if statement detects “true” twice.

My question is: How can I restructure my code?

Should I put lines 1206-1214 into the DeselectButton() function?
Before:


After:

But now, it doesn’t know the saveTransformationButtonChoicesAndSetThemToFalse() function, which means I have to move the DeselectButton() function all the way to the bottom, which means it can’t be called anywhere else in the script, and now this has turned into one big jumbled mess. Maybe I should use a module script? But that doesn’t solve anything… I don’t know. Please help…

Thanks!

might want to use a debounce technique …

local db = true
toolBarButtonsArray["Move"]:GetAttributeChangedSignal("selected"):Connect(function()
	if db then db = false

		local selected = toolBarButtonsArray["Move"]:GetAttribute("selected")
		--print(selected)
		if selected == true then
			print("select movetoolORrotatetoolFunction")
			movetoolORrotatetoolFunction(movetool)
		elseif selected == false then
			saveTransformationButtonChoicesAndSetThemToFalse()
			TransformationButtons.Visible = false
			movetool.Visible = false
			CenterPartWithArrows.CFrame = CFrame.new(0, -10, 0)
		end
     
    	task.wait(0.33) -- whatever works here
		db = true
	end
end)

Just make the functions global, so that I can put them at the bottom and not worry about them… that was simple enough :p