Hello, I’ve been pretty confused on this topic about “How do I stop a loop”
Loop examples:
while true do
while wait() do
So yeah, I just wanna know how to stop a loop inside of a script.
Hello, I’ve been pretty confused on this topic about “How do I stop a loop”
Loop examples:
while true do
while wait() do
So yeah, I just wanna know how to stop a loop inside of a script.
You could put conditions or just use break
.
How do I insert a break into a while wait() or while true
local secondsElapsed = 0
local timeout = 5
while true do
print("Looping...")
task.wait(1)
secondsElapsed += 1
if secondsElapsed == timeout then
break
end
end
print("Loop ended; moving on!")
[example from the hub]
You can either use the break
global like @Valkyrop said, Or a better alternative is to use a coroutine. Coroutines can be created, resumed or yielded anytime you want to.
-- Creates a new Coroutine
local LoopCoroutine = coroutine.create(function()
while task.wait(1) do
print("We're Looping!")
end
end)
task.spawn(LoopCoroutine) -- Starts the LoopCoroutine
task.wait(5)
task.cancel(LoopCoroutine) -- Stops the LoopCoroutine
They both worked but this one made it simpler!