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 .
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 would spin millions of times a second — printing "tick" so fast it locks up your game. A 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 is false, the stops, and the continues. This is exactly how countdown timers work in games.
A that must end needs its to change: something inside the 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 always runs at least once. Use it when you need the check to happen after some work — like waiting for a that starts false.
While loops check the condition they run; repeat loops check
end in two ways: a goes false (while and repeat), or you force an exit with break (rarely needed in this course).
An infinite with no task.wait will freeze Studio, and you'll have to stop the game manually. When you're testing a and the game hangs, the first thing to check is: is there a wait, and does my 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 that counts a fixed number of times — for.