A while loop repeats while its condition stays true.

condition first The condition is checked before each iteration, so the loop may run zero or more times.

While Loop

start
while_loop.lua
Replay: real traced execution (multi-file project)
local start = 3
local counter = start
local total = 0

while counter > 0 do
  total = total + counter
  counter = counter - 1
end

print("start=" .. start)
print("total=" .. total)
local start = 1
local counter = start
local total = 0

while counter > 0 do
  total = total + counter
  counter = counter - 1
end

print("start=" .. start)
print("total=" .. total)
local start = 5
local counter = start
local total = 0

while counter > 0 do
  total = total + counter
  counter = counter - 1
end

print("start=" .. start)
print("total=" .. total)
  1. start ← 3, counter ← 3, total ← 0

    1local start→ 3 = 3 --@start=1, 52local counter→ 3 = start33local total→ 0 = 0
  2. total ← 3, counter ← 2

    pass 1 of 3
    5while counter3 > 0 do6  total→ 3 = total + counter37  counter→ 2 = counter - 18end
    All 3 passes — pass 1 is the card above
    passtotalcounter
    10 33 2
    23 52 1
    35 61 0
  3. print("start=" .. start)

    10print("start=" .. start3)11print("total=" .. total6)
    outputstart=3
    total=6
  1. start ← 1, counter ← 1, total ← 0

    1local start→ 1 = 12local counter→ 1 = start13local total→ 0 = 0
  2. total ← 1, counter ← 0

    5while counter1 > 0 do6  total→ 1 = total + counter17  counter→ 0 = counter - 18end
  3. print("start=" .. start)

    10print("start=" .. start1)11print("total=" .. total1)
    outputstart=1
    total=1
  1. start ← 5, counter ← 5, total ← 0

    1local start→ 5 = 52local counter→ 5 = start53local total→ 0 = 0
  2. total ← 5, counter ← 4

    pass 1 of 5
    5while counter5 > 0 do6  total→ 5 = total + counter57  counter→ 4 = counter - 18end
    All 5 passes — pass 1 is the card above
    passtotalcounter
    10 55 4
    25 94 3
    39 123 2
    412 142 1
    514 151 0
  3. print("start=" .. start)

    10print("start=" .. start5)11print("total=" .. total15)
    outputstart=5
    total=15

Count Down the Total

  1. start is 3.
  2. counter begins at 3.
  3. The loop runs while counter > 0.
  4. Each pass adds counter, then subtracts 1.
  5. The final total is 6. | Counter | Running total | | --- | --- | | 3 | 3 | | 2 | 5 | | 1 | 6 |

Exercise: while_loop.lua

Use a while loop to count down from a start value and print the total