Run code forever, or until a condition changes — the heartbeat of every game.
Every living game has a heartbeat: something that runs constantly, checking and updating. The sun rotating, a shop restocking, enemies respawning. That heartbeat is a loop.
while true do
print("tick")
task.wait(1)
end
while true do — "keep going as long as true is true", i.e. forever.do and end run.task.wait(1) — pause for 1 second before the next round.Without the task.wait, the loop would spin millions of times a second — printing "tick" so fast it locks up your game. A loop that runs forever needs a pause. Think of while true as breathing: the wait is the breath.
What is wrong with this loop?
You don't need forever. This counts down:
local count = 5
while count > 0 do
print(count)
count = count - 1
task.wait(1)
end
print("Go!")
Each pass, count drops by one. The moment it hits 0, the condition is false, the loop stops, and the script continues. This is exactly how countdown timers work in games.
A loop that must end needs its condition to change: something inside the loop must move the value toward false. No change, no end.
repeat runs the block first, then checks:
repeat
task.wait(0.5)
print("checking...")
until coins >= 100
The difference: while checks before each run, repeat checks after. So a repeat loop always runs at least once. Use it when you need the check to happen after some work — like waiting for a condition that starts false.
While loops check the condition they run; repeat loops check
Loops end in two ways: a condition goes false (while and repeat), or you force an exit with break (rarely needed in this course).
An infinite loop with no task.wait will freeze Studio, and you'll have to stop the game manually. When you're testing a loop and the game hangs, the first thing to check is: is there a wait, and does my condition ever turn false?
Write a while loop that counts 3, 2, 1 (with a 1-second wait each), then a print of 'Go!' after it ends.
-- countdown from 3
Next: a loop that counts a fixed number of times — for.