Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
Lunaify 66
4 years ago

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

Log in to vote
1
Answered by 4 years ago

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)
0
thanks Lunaify 66 — 4y
Ad

Answer this question