Foundations
Loops
Loops repeat a block while a counter changes.
for loop
A numeric `for` loop visits each number from the start value through the end value.
Loops
loops.lua
Replay: real traced execution (multi-file project)
local limit = 4
local total = 0
for number = 1, limit do
total = total + number
end
print("limit=" .. limit)
print("total=" .. total)
local limit = 2
local total = 0
for number = 1, limit do
total = total + number
end
print("limit=" .. limit)
print("total=" .. total)
local limit = 6
local total = 0
for number = 1, limit do
total = total + number
end
print("limit=" .. limit)
print("total=" .. total)
limit ← 4, total ← 0
1local limit→ 4 = 4 --@limit=2, 62local total→ 0 = 0total ← 1
pass 1 of 44for number1 = 1, limit4 do5 total→ 1 = total + number16endAll 4 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 print("limit=" .. limit)
8print("limit=" .. limit4)9print("total=" .. total10)outputlimit=4 total=10
limit ← 2, total ← 0
1local limit→ 2 = 22local total→ 0 = 0total ← 1
pass 1 of 24for number1 = 1, limit2 do5 total→ 1 = total + number16endtotal ← 3
pass 2 of 24for number2 = 1, limit2 do5 total→ 3 = total + number26endprint("limit=" .. limit)
8print("limit=" .. limit2)9print("total=" .. total3)outputlimit=2 total=3
limit ← 6, total ← 0
1local limit→ 6 = 62local total→ 0 = 0total ← 1
pass 1 of 64for number1 = 1, limit6 do5 total→ 1 = total + number16endAll 6 passes — pass 1 is the card above pass numbertotal1 1 0 → 1 2 2 1 → 3 3 3 3 → 6 4 4 6 → 10 5 5 10 → 15 6 6 15 → 21 print("limit=" .. limit)
8print("limit=" .. limit6)9print("total=" .. total21)outputlimit=6 total=21
What Happens
limitstarts at4.totalstarts at0.- The numeric
forloop visits1,2,3, and4. - Each number is added to
total. - The program prints
limit=4andtotal=10.
Loop Picture
| limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |
Try It
Exercise: loops.lua
Reproduce total=10 for limit 4, then use the pinned limits 2 and 6 to predict each total.