Functions and loops, lesson 15
while loops and waiting
Goal: Repeat until something changes, without freezing the game.
about 6 min3 practice exercises
A while loop repeats for as long as its condition is true.
local countdown = 3
while countdown > 0 do
print(countdown)
countdown -= 1
task.wait(1)
end
print("Round over")
Each pass checks countdown > 0, prints, subtracts 1 and then pauses for one second with task.wait(1).
Two rules keep while loops safe:
- Something inside must change the condition. Without
countdown -= 1the condition stays true forever. - A loop that runs for a long time must wait. A loop with no
task.wait()never gives Roblox a chance to do anything else, and the script freezes.
break leaves a loop early, and continue skips to the next pass.
Later you will see that many things people write loops for, such as "check whether a player touched the coin", are better done with events.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.