Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how would you make a while loop start all over again if a certain condition is met?

how could i make it so when a certain condition is met, the loop starts all over again from the top??



local Amount = game:GetService("ReplicatedStorage"):WaitForChild("Amount")


while wait(1) do
	
	if Amount.Value < 5 then
		--// make the loop start all over again(so it makes the timer start from 20 again)
	end
	
	
	for i = 20,0,-1 do
		print(i)
		wait(1)
	end
		
end


1 answer

✓ Accepted answer

You can use a recursive function, a function that calls itself from within itself as such:

local Amount = game:GetService("ReplicatedStorage"):WaitForChild("Amount")

local function BeginTimer()
	while wait(1) do
		if Amount.Value < 5 then
			BeginTimer()
			break -- Make sure the ongoing loop stops
		end
		for t = 20,0,-1 do
			print(t)
			wait(1)
		end
	end
end)

BeginTimer()

However, I'm not sure this is the behaviour you're expecting. This will cause the loop to reset every 20 seconds, no matter what Amount.Value is. Incase you want this to occur only once each time the value goes below 5, you can listen for changes and then start the timer:

local Amount = game:GetService("ReplicatedStorage"):WaitForChild("Amount")
local timerOff = true

Amount.Changed:Connect(function()
	if Amount.Value < 5 and timerOff then
		timerOff = false
		for t = 20,0,-1 do
			print(t)
			wait(1)
		end
		timerOff = true
	end
end)

1 comment

0

thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.