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

bonus
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)
  1. bonus ← 4, total ← 0

    1local bonus→ 4 = 4 --@bonus=1, 72local total→ 0 = 0
  2. total ← 3

    pass 1 of 3
    4for _1, points3 in ipairs({3, bonus4, 5}) do5  total→ 3 = total + points36end
    All 3 passes — pass 1 is the card above
    pass_pointstotal
    1130 3
    2243 7
    3357 12
  3. print("bonus=" .. bonus)

    8print("bonus=" .. bonus4)9print("total=" .. total12)
    outputbonus=4
    total=12
  1. bonus ← 1, total ← 0

    1local bonus→ 1 = 12local total→ 0 = 0
  2. total ← 3

    pass 1 of 3
    4for _1, points3 in ipairs({3, bonus1, 5}) do5  total→ 3 = total + points36end
    All 3 passes — pass 1 is the card above
    pass_pointstotal
    1130 3
    2213 4
    3354 9
  3. print("bonus=" .. bonus)

    8print("bonus=" .. bonus1)9print("total=" .. total9)
    outputbonus=1
    total=9
  1. bonus ← 7, total ← 0

    1local bonus→ 7 = 72local total→ 0 = 0
  2. total ← 3

    pass 1 of 3
    4for _1, points3 in ipairs({3, bonus7, 5}) do5  total→ 3 = total + points36end
    All 3 passes — pass 1 is the card above
    pass_pointstotal
    1130 3
    2273 10
    33510 15
  3. print("bonus=" .. bonus)

    8print("bonus=" .. bonus7)9print("total=" .. total15)
    outputbonus=7
    total=15

Follow the Sum

  1. bonus starts as 4.
  2. total starts as 0.
  3. The loop visits values 3, 4, and 5.
  4. Each value is added to total.
  5. 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.