break exits the nearest loop immediately.

early exit Use `break` when the loop has found enough information and should stop.

Break Loop

stopAt
break_loop.lua
Replay: real traced execution (multi-file project)
local stopAt = 3
local total = 0

for number = 1, 6 do
  if number == stopAt then
    break
  end
  total = total + number
end

print("stopAt=" .. stopAt)
print("total=" .. total)
local stopAt = 2
local total = 0

for number = 1, 6 do
  if number == stopAt then
    break
  end
  total = total + number
end

print("stopAt=" .. stopAt)
print("total=" .. total)
local stopAt = 5
local total = 0

for number = 1, 6 do
  if number == stopAt then
    break
  end
  total = total + number
end

print("stopAt=" .. stopAt)
print("total=" .. total)
  1. stopAt ← 3, total ← 0

    1local stopAt→ 3 = 3 --@stopAt=2, 52local total→ 0 = 0
  2. total ← 1

    pass 1 of 3
    4for number1 = 1, 6 do5  if number == stopAt then6    break7  end8  total→ 1 = total + number19end
    All 3 passes — pass 1 is the card above
    passnumberstopAttotal
    110 1
    221 3
    333
  3. if number == stopAt then

    4for number = 1, 6 do5  if number3 == stopAt3 then6    break7  end
  4. print("stopAt=" .. stopAt)

    11print("stopAt=" .. stopAt3)12print("total=" .. total3)
    outputstopAt=3
    total=3
  1. stopAt ← 2, total ← 0

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

    pass 1 of 2
    4for number1 = 1, 6 do5  if number == stopAt then6    break7  end8  total→ 1 = total + number19end
  3. number = 1, 6 do

    pass 2 of 2
    4for number2 = 1, 6 do5  if number == stopAt then6    break
  4. if number == stopAt then

    4for number = 1, 6 do5  if number2 == stopAt2 then6    break7  end
  5. print("stopAt=" .. stopAt)

    11print("stopAt=" .. stopAt2)12print("total=" .. total1)
    outputstopAt=2
    total=1
  1. stopAt ← 5, total ← 0

    1local stopAt→ 5 = 52local total→ 0 = 0
  2. total ← 1

    pass 1 of 5
    4for number1 = 1, 6 do5  if number == stopAt then6    break7  end8  total→ 1 = total + number19end
    All 5 passes — pass 1 is the card above
    passnumberstopAttotal
    110 1
    221 3
    333 6
    446 10
    555
  3. if number == stopAt then

    4for number = 1, 6 do5  if number5 == stopAt5 then6    break7  end
  4. print("stopAt=" .. stopAt)

    11print("stopAt=" .. stopAt5)12print("total=" .. total10)
    outputstopAt=5
    total=10

Stop Before Adding Three

  1. stopAt starts at 3.
  2. The loop begins with number = 1.
  3. Values before 3 are added to total.
  4. When number is 3, break exits before adding it. | Number | Action | Total | | --- | --- | --- | | 1 | add | 1 | | 2 | add | 3 | | 3 | break | 3 |

Exercise: break_loop.lua

Use break to stop at a chosen number and print the total before that number