Control Flow Details
Break Loop
break exits the nearest loop immediately.
early exit
Use `break` when the loop has found enough information and should stop.
Break Loop
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)
stopAt ← 3, total ← 0
1local stopAt→ 3 = 3 --@stopAt=2, 52local total→ 0 = 0total ← 1
pass 1 of 34for number1 = 1, 6 do5 if number == stopAt then6 break7 end8 total→ 1 = total + number19endAll 3 passes — pass 1 is the card above pass numberstopAttotal1 1 — 0 → 1 2 2 — 1 → 3 3 3 3 — if number == stopAt then
4for number = 1, 6 do5 if number3 == stopAt3 then6 break7 endprint("stopAt=" .. stopAt)
11print("stopAt=" .. stopAt3)12print("total=" .. total3)outputstopAt=3 total=3
stopAt ← 2, total ← 0
1local stopAt→ 2 = 22local total→ 0 = 0total ← 1
pass 1 of 24for number1 = 1, 6 do5 if number == stopAt then6 break7 end8 total→ 1 = total + number19endnumber = 1, 6 do
pass 2 of 24for number2 = 1, 6 do5 if number == stopAt then6 breakif number == stopAt then
4for number = 1, 6 do5 if number2 == stopAt2 then6 break7 endprint("stopAt=" .. stopAt)
11print("stopAt=" .. stopAt2)12print("total=" .. total1)outputstopAt=2 total=1
stopAt ← 5, total ← 0
1local stopAt→ 5 = 52local total→ 0 = 0total ← 1
pass 1 of 54for number1 = 1, 6 do5 if number == stopAt then6 break7 end8 total→ 1 = total + number19endAll 5 passes — pass 1 is the card above pass numberstopAttotal1 1 — 0 → 1 2 2 — 1 → 3 3 3 — 3 → 6 4 4 — 6 → 10 5 5 5 — if number == stopAt then
4for number = 1, 6 do5 if number5 == stopAt5 then6 break7 endprint("stopAt=" .. stopAt)
11print("stopAt=" .. stopAt5)12print("total=" .. total10)outputstopAt=5 total=10
Stop Before Adding Three
stopAtstarts at3.- The loop begins with
number = 1. - Values before
3are added tototal. - When
numberis3,breakexits 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