How do I basically stop a loop?

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.

1 Like

You could put conditions or just use break.

How do I insert a break into a while wait() or while true

Oops!)

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]

1 Like

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
5 Likes

They both worked but this one made it simpler! :+1:

1 Like