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

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

    1local limit→ 4 = 4 --@limit=2, 62local total→ 0 = 0
  2. total ← 1

    pass 1 of 4
    4for number1 = 1, limit4 do5  total→ 1 = total + number16end
    All 4 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
  3. print("limit=" .. limit)

    8print("limit=" .. limit4)9print("total=" .. total10)
    outputlimit=4
    total=10
  1. limit ← 2, total ← 0

    1local limit→ 2 = 22local total→ 0 = 0
  2. total ← 1

    pass 1 of 2
    4for number1 = 1, limit2 do5  total→ 1 = total + number16end
  3. total ← 3

    pass 2 of 2
    4for number2 = 1, limit2 do5  total→ 3 = total + number26end
  4. print("limit=" .. limit)

    8print("limit=" .. limit2)9print("total=" .. total3)
    outputlimit=2
    total=3
  1. limit ← 6, total ← 0

    1local limit→ 6 = 62local total→ 0 = 0
  2. total ← 1

    pass 1 of 6
    4for number1 = 1, limit6 do5  total→ 1 = total + number16end
    All 6 passes — pass 1 is the card above
    passnumbertotal
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
  3. print("limit=" .. limit)

    8print("limit=" .. limit6)9print("total=" .. total21)
    outputlimit=6
    total=21

What Happens

  1. limit starts at 4.
  2. total starts at 0.
  3. The numeric for loop visits 1, 2, 3, and 4.
  4. Each number is added to total.
  5. The program prints limit=4 and total=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.