While Loop

A for loop is good when you know how many rounds you need. Sometimes you do not know that in advance. A while loop keeps running as long as a condition is true.

This program doubles an amount until it reaches 100, and counts the doublings:

local amount = 5
local doublings = 0
while amount < 100 do
    amount = amount * 2
    doublings = doublings + 1
end
print("Amount: " .. amount)
print("Doublings: " .. doublings)

Output:

Amount: 160
Doublings: 5

The shape is while condition do ... end. Before each round, Lua checks the condition. If it is true, the block runs, and Lua checks again. If it is false, the loop ends and the program goes on after end.

Here the amount went 5, 10, 20, 40, 80, 160. Then 160 < 100 was false, so the loop stopped. You did not need to know the number of rounds before you started. The loop found it.

The loop that never ends

Something inside the block must move the condition toward false. In the example, that is amount = amount * 2. Remove that line and amount stays 5 forever:

local amount = 5
local doublings = 0
while amount < 100 do
    doublings = doublings + 1
end
print("Doublings: " .. doublings)

The condition is always true, so the loop never ends. This is called an infinite loop. The program prints nothing and keeps running. When you run it here, it is stopped after about 5 seconds with the message Time limit exceeded.

Each time you write a while loop, find the line in the block that brings it closer to the end.

Zero rounds is possible

Lua checks the condition before the first round. If the condition is false from the start, the block never runs:

local amount = 500
while amount < 100 do
    amount = amount * 2
end
print("Amount: " .. amount)

Output:

Amount: 500

Often that is what you want. When you need the block to run at least once, Lua has a different loop for that, the repeat loop in the next lesson.

In the exercise, use a while loop to count down from n to 1 before a rocket launch.