Control Flow Details
While Loop
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
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)
start ← 3, counter ← 3, total ← 0
1local start→ 3 = 3 --@start=1, 52local counter→ 3 = start33local total→ 0 = 0total ← 3, counter ← 2
pass 1 of 35while counter3 > 0 do6 total→ 3 = total + counter37 counter→ 2 = counter - 18endAll 3 passes — pass 1 is the card above pass totalcounter1 0 → 3 3 → 2 2 3 → 5 2 → 1 3 5 → 6 1 → 0 print("start=" .. start)
10print("start=" .. start3)11print("total=" .. total6)outputstart=3 total=6
start ← 1, counter ← 1, total ← 0
1local start→ 1 = 12local counter→ 1 = start13local total→ 0 = 0total ← 1, counter ← 0
5while counter1 > 0 do6 total→ 1 = total + counter17 counter→ 0 = counter - 18endprint("start=" .. start)
10print("start=" .. start1)11print("total=" .. total1)outputstart=1 total=1
start ← 5, counter ← 5, total ← 0
1local start→ 5 = 52local counter→ 5 = start53local total→ 0 = 0total ← 5, counter ← 4
pass 1 of 55while counter5 > 0 do6 total→ 5 = total + counter57 counter→ 4 = counter - 18endAll 5 passes — pass 1 is the card above pass totalcounter1 0 → 5 5 → 4 2 5 → 9 4 → 3 3 9 → 12 3 → 2 4 12 → 14 2 → 1 5 14 → 15 1 → 0 print("start=" .. start)
10print("start=" .. start5)11print("total=" .. total15)outputstart=5 total=15
Count Down the Total
startis3.counterbegins at3.- The loop runs while
counter > 0. - Each pass adds
counter, then subtracts1. - 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