While True Do Loop Not Breaking - Scripting Help

Hi, I don’t know what I’m doing wrong. The code starts the loop but doesn’t end it. What’s the problem?!?

local car = script.Parent.Car.Value
local player = game.Players.LocalPlayer
local UserInputService = game:GetService("UserInputService")
local LeftBlinkerDB = false
local RightBlinkerDB = false
local Sound = car.Body.Sounds:WaitForChild("Blinkers")

local function ToggleBlinkers(Toggle, Blinker)
	while true do
		wait(0.5)
		print("Click")
		wait(0.5)
		print("Clock")
		
		if Toggle == false then
			break
		end
	end
end

UserInputService.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.E and not gameProcessed then
			if RightBlinkerDB == false then
				RightBlinkerDB = true
			else
				RightBlinkerDB = false
			end
			ToggleBlinkers(RightBlinkerDB)
			print(RightBlinkerDB)
		end
	end
end)

UserInputService.InputBegan:Connect(function(input, gameProcessed)
	if input.UserInputType == Enum.UserInputType.Keyboard then
		if input.KeyCode == Enum.KeyCode.Q and not gameProcessed then
			if LeftBlinkerDB == false then
				LeftBlinkerDB = true
			else
				LeftBlinkerDB = false
			end
			ToggleBlinkers(LeftBlinkerDB)
			print(LeftBlinkerDB)
		end
	end
end)


1 Like

If I’m not wrong I believe when you put a value into a function as an argument it uses a copy of the original value, and doesnt actually see the changes you have made outside of the function you are using it in.

^ You need to use a global state. E.g,

local Toggle = false

local function Loop()
    Toggle = not Toggle

    while Toggle do
        -- ...
    end
end

I see, but I am running the function every time I change the variable

Let me try that. Thankyou for your reply.

Well, would you look at that! It works. Thankyou. I think I understand how the code works too which will be very helpful for me. Thankyou!

2 Likes