Iterators and Generic For
Sum Values
A generic for loop can ignore an index when only the values matter.
ignored values
The `_` name is a convention for a loop result you do not plan to use.
Sum Values
sum_values.lua
Replay: real traced execution (multi-file project)
local bonus = 4
local total = 0
for _, points in ipairs({3, bonus, 5}) do
total = total + points
end
print("bonus=" .. bonus)
print("total=" .. total)
local bonus = 1
local total = 0
for _, points in ipairs({3, bonus, 5}) do
total = total + points
end
print("bonus=" .. bonus)
print("total=" .. total)
local bonus = 7
local total = 0
for _, points in ipairs({3, bonus, 5}) do
total = total + points
end
print("bonus=" .. bonus)
print("total=" .. total)
bonus ← 4, total ← 0
1local bonus→ 4 = 4 --@bonus=1, 72local total→ 0 = 0total ← 3
pass 1 of 34for _1, points3 in ipairs({3, bonus4, 5}) do5 total→ 3 = total + points36endAll 3 passes — pass 1 is the card above pass _pointstotal1 1 3 0 → 3 2 2 4 3 → 7 3 3 5 7 → 12 print("bonus=" .. bonus)
8print("bonus=" .. bonus4)9print("total=" .. total12)outputbonus=4 total=12
bonus ← 1, total ← 0
1local bonus→ 1 = 12local total→ 0 = 0total ← 3
pass 1 of 34for _1, points3 in ipairs({3, bonus1, 5}) do5 total→ 3 = total + points36endAll 3 passes — pass 1 is the card above pass _pointstotal1 1 3 0 → 3 2 2 1 3 → 4 3 3 5 4 → 9 print("bonus=" .. bonus)
8print("bonus=" .. bonus1)9print("total=" .. total9)outputbonus=1 total=9
bonus ← 7, total ← 0
1local bonus→ 7 = 72local total→ 0 = 0total ← 3
pass 1 of 34for _1, points3 in ipairs({3, bonus7, 5}) do5 total→ 3 = total + points36endAll 3 passes — pass 1 is the card above pass _pointstotal1 1 3 0 → 3 2 2 7 3 → 10 3 3 5 10 → 15 print("bonus=" .. bonus)
8print("bonus=" .. bonus7)9print("total=" .. total15)outputbonus=7 total=15
Follow the Sum
bonusstarts as4.totalstarts as0.- The loop visits values
3,4, and5. - Each value is added to
total. - The final total is
12. | value added | running total | | --- | --- | | 3 | 3 | | 4 | 7 | | 5 | 12 |
Exercise: sum_values.lua
Reproduce bonus=4 and total=12, then use the pinned bonus variants 1 and 7 to predict total=9 and total=15.