18. Loops

The other way out of repeating yourself is the loop: a block of code that runs over and over. Lua has three loop shapes, all covered here, plus break for stopping early.

while — repeat as long as the condition is true

while is the most general loop. It checks a condition, runs the block if true, then checks again — repeating until it is false.

local count = 10
while count > 0 do
    print(count)
    count = count - 1
end
print("Blast off!")

Run order:

  1. Check count > 0. It is 10, so true.
  2. Print 10, set count to 9.
  3. Back to step 1. count is 9, still true. Print, decrement.
  4. Repeat until count is 0. The condition fails, the loop exits, and print("Blast off!") runs once.

Inside the body, change a value the condition depends on, or the loop never ends. An infinite loop locks the terminal. Stop it with Ctrl + C.

repeat ... until — runs the body first, then checks

repeat is while's mirror image. It runs the body at least once, then checks, ending when the condition becomes true — the opposite of while.

local count = 1
repeat
    print(count)
    count = count + 1
until count > 5

Output:

1
2
3
4
5

Use repeat when the loop must run at least once — like asking a question and re-asking on bad input. You will use this in the Part 4 mini-project.

for — repeat a known number of times

The third loop is the numeric for — the right tool for running a known number of times. The shape:

for i = start, stop do
    -- body
end

i is a fresh variable, alive only inside the loop. Lua sets it to start, adds 1 each round, and stops once it would pass stop. Both ends are included.

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

Output:

1
2
3
4
5

A step

A third value after stop is the step — how much i changes each round. The default is 1; change it to skip or count backwards:

for i = 0, 100, 10 do      -- 0, 10, 20, ... 100
    io.write(i .. " ")
end
print()                    -- a blank line at the end

for i = 10, 1, -1 do       -- 10, 9, 8, ... 1
    io.write(i .. " ")
end
print()

The step needs the right sign — positive going up, negative going down. A step of 0 makes an infinite loop, and Lua will tell you.

Open exercises/18/01-for-table.lua. It prints the multiplication table of 7, from 7 * 1 to 7 * 10. Change it to print the table of any other number.

break — leave the loop early

Any of the three loops can be cut short with break, which jumps straight to whatever comes after the loop.

local n = 1
while true do
    if n * n > 100 then
        break
    end
    n = n + 1
end
print("First number whose square is over 100 is " .. n)

while true do ... end has no built-in exit; the only way out is break (or an error). Use it when the exit test is too complicated for a single comparison at the top.

Homework

Problem 1 — Count to 20

Open exercises/18/homework/01-count-to-20.lua. Use a while loop to print 1 to 20, each on its own line.

Problem 2 — Multiplication table of 7

Open exercises/18/homework/02-mult-table-7.lua. Use a numeric for loop to print the multiplication table of 7, from 7 * 1 to 7 * 12, in this shape:

7 * 1 = 7
7 * 2 = 14
...
7 * 12 = 84

Problem 3 — Stop at the threshold

Open exercises/18/homework/03-stop-at-threshold.lua. Loop from 1, adding each number to a running total. Stop once the total exceeds 100, then print the total and the counter value at that moment.

Challenge — Sum 1..N

Open exercises/18/homework/04-sum-1-to-n.lua. Prompt for a positive whole number n. Compute 1 + 2 + 3 + ... + n with a for loop and a running total. Print:

Sum from 1 to N is S

Then print the formula n * (n + 1) / 2 on the next line — the closed-form answer. The two should agree.

Stuck or finished? Open the homework solutions page.