← Back to course
easy ✦ 75 Studs

For Loops

Count a known number of times cleanly with a numeric for loop.

Your while loop runs until you tell it to stop. That is perfect when you do not know how many times you will repeat. But a ton of the time you DO know the count: do this 10 times, run through 5 enemies, count down from 5. For those, a for loop is cleaner, because it does the counting for you.

Here is the shape:

for i = 1, 5 do
  print(i)
end

That prints 1, 2, 3, 4, 5, each on its own line. The variable i is the counter. It starts at the first number, climbs by 1 each time around, and the loop quits automatically once it passes the second number. No wait() needed to keep it safe, because a for loop with a fixed range cannot run forever. It knows exactly when to stop.

There is a third slot too, the step, and it is how you count by something other than 1:

for i = 5, 1, -1 do
  print(i)
end

The -1 makes i go DOWN instead of up, so you get 5, 4, 3, 2, 1. That is a countdown. You could just as easily use 2 to count every other number, or 10 to jump by tens. The step is your speed and direction dial.

Why reach for for over while? When the number of repeats is known, for says it right in the first line, so anyone reading your code instantly sees the plan. Less to track, fewer bugs, and zero chance of an accidental forever loop.

Now make it yours: print the exact countdown for this lesson (count down to 1, then print Blast off). After that, try a times table row, like for i = 1, 12 do print("7 times " .. i .. " is " .. 7 * i) end, and watch a whole multiplication table fall out of six lines of code.

Output
Click Run to see your output.