← Back to course
review ✦ 50 Studs

While Intro

Repeat work as long as a condition stays true with a while loop.

A while loop is the laziest, most useful tool you’ll learn this week. It says: “as long as this condition is true, do the body again.” When the condition finally turns false, the loop stops and your program moves on.

local energy = 3
while energy > 0 do
  print("Zap! Energy left: " .. energy)
  energy = energy - 1
end
print("Out of energy.")

Trace that in your head. Energy starts at 3, prints, drops to 2, checks again, prints, and so on until it hits 0, which makes the condition false. That last line about updating the variable is the whole game. It’s the part that eventually ends the loop.

Here’s the trap, and you’ll fall into it at least once (everybody does, it’s a rite of passage): if you forget to change the variable, the condition stays true forever and the loop never ends. We call that an infinite loop. It’s not scary, it just means you missed the line that makes progress toward stopping.

Now make it yours: start count at 1 and use a while loop to print 1 through 5. Then try counting backward from 5 to 1 by subtracting instead.

Output
Click Run to see your output.