repeat ... until runs the body before checking the stop condition.

condition last A repeat loop always runs at least once because the condition comes after the body.

Repeat Until

target
repeat_until.lua
Replay: real traced execution (multi-file project)
local target = 3
local count = 0

repeat
  count = count + 1
until count >= target

print("target=" .. target)
print("count=" .. count)
local target = 1
local count = 0

repeat
  count = count + 1
until count >= target

print("target=" .. target)
print("count=" .. count)
local target = 5
local count = 0

repeat
  count = count + 1
until count >= target

print("target=" .. target)
print("count=" .. count)
  1. target ← 3, count ← 0

    1local target→ 3 = 3 --@target=1, 52local count→ 0 = 0
  2. count ← 1

    pass 1 of 3
    4repeat5  count→ 1 = count + 16until count >= target
    All 3 passes — pass 1 is the card above
    passcount
    10 1
    21 2
    32 3
  3. print("target=" .. target)

    8print("target=" .. target3)9print("count=" .. count3)
    outputtarget=3
    count=3
  1. target ← 1, count ← 0

    1local target→ 1 = 12local count→ 0 = 0
  2. count ← 1

    4repeat5  count→ 1 = count + 16until count >= target
  3. print("target=" .. target)

    8print("target=" .. target1)9print("count=" .. count1)
    outputtarget=1
    count=1
  1. target ← 5, count ← 0

    1local target→ 5 = 52local count→ 0 = 0
  2. count ← 1

    pass 1 of 5
    4repeat5  count→ 1 = count + 16until count >= target
    All 5 passes — pass 1 is the card above
    passcount
    10 1
    21 2
    32 3
    43 4
    54 5
  3. print("target=" .. target)

    8print("target=" .. target5)9print("count=" .. count5)
    outputtarget=5
    count=5

Repeat Until Target

  1. target starts at 3.
  2. count starts at 0.
  3. The repeat body runs and adds 1.
  4. The loop stops when count >= target.
  5. The final count is 3. | Pass | Count after pass | Stop? | | --- | --- | --- | | 1 | 1 | no | | 2 | 2 | no | | 3 | 3 | yes |

Exercise: repeat_until.lua

Use repeat until to count up until count reaches the target