Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 32 ยท Control Flow

Loops

Learn Lua's three loops: while, repeat-until and the numeric for with a step, plus break, the goto continue idiom and how loop variables are scoped.

A loop repeats a block of code. Lua gives you three kinds: while, repeat ... until, and for. The for loop itself comes in two flavors, the numeric one you will meet in this lesson and the generic one that walks over tables, which gets its own lesson next (Iterating with pairs and ipairs).

All of them use do ... end or repeat ... until to mark their bodies, and none of them needs parentheses. Lua is not installed on this site, so the Lua listings are read-only and show real behavior; the runnable examples are JavaScript stand-ins that follow the same steps. Where Lua differs from JavaScript, the text says so.

while

while tests its condition before every pass, so the body may run zero times:

LUA
local n = 1
while n <= 3 do
  print("pass " .. n)
  n = n + 1
end
-- pass 1
-- pass 2
-- pass 3

Remember that only nil and false end the loop, so while 0 do would run forever (0 is true in Lua). There is no ++ or += in Lua either; write n = n + 1.

repeat ... until

repeat runs the body first and tests afterwards, so it always runs at least once. Notice that the loop continues until the condition becomes true, which is the opposite of while:

LUA
local tries = 0
repeat
  tries = tries + 1
  print("try " .. tries)
until tries >= 3

A special rule makes this loop handy: the condition can see the local variables declared inside the body. In most languages the variable of a do-while loop must be declared outside:

LUA
local i = 0
repeat
  i = i + 1
  local square = i * i      -- a local of the loop body
until square > 50           -- the condition can read it
print(i, square)            --> 8   64

The numeric for loop

The most common loop counts. The syntax is for var = start, stop, step do:

LUA
for i = 1, 5 do
  io.write(i, " ")
end
print()
--> 1 2 3 4 5

Both ends are inclusive: 1, 5 visits five numbers, including 5. The step is optional and defaults to 1. It may be negative to count down, and it may not be zero (that is an error):

LUA
for i = 10, 0, -5 do
  print(i)               -- 10, 5, 0
end

for x = 0, 1, 0.25 do
  print(x)               -- 0.0, 0.25, 0.5, 0.75, 1.0
end

When start and step are both integers the loop variable is an integer. As soon as one of them is a float (as in the second loop), the variable is a float, which is why 0.0 prints with a decimal point. If the start is already beyond the stop value in the step's direction, the body never runs: for i = 5, 1 do ... end does nothing, because the default step is +1. Write for i = 5, 1, -1 to count down.

Three facts about the numeric for are worth remembering:

  1. The start, stop and step expressions are evaluated once, before the loop begins. If the stop value is #items and you remove items inside the loop, the loop does not notice.
  2. The loop variable is a fresh local for each pass, visible only inside the body. After the loop it is out of scope.
  3. Assigning to the loop variable changes only that pass's copy, not the sequence of values. Do not rely on it. If you need to skip ahead, use a while loop.

Pick the right loop

while Test first. May run zero times.
repeat-until Test last. Runs at least once.
numeric for Counts from start to stop by step.
generic for Walks tables. Next lesson.
1 / 2

Try it: counting and stepping

This JavaScript stand-in builds the sequence the way Lua's numeric for does: inclusive end, a possibly negative step, and bounds fixed before the first pass.

JS Numeric for stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

break

break leaves the innermost loop immediately. In Lua 5.4 it can appear anywhere inside the loop body:

LUA
local numbers = {4, 8, 15, 16, 23, 42}
local firstOdd
for i = 1, #numbers do
  if numbers[i] % 2 == 1 then
    firstOdd = numbers[i]
    break
  end
end
print(firstOdd)   --> 15

Tables and the # operator are explained in Tables as Arrays and Dictionaries; here #numbers is simply the number of items, 6.

Skipping an iteration: goto continue

Lua has no continue keyword. The accepted idiom uses goto with a label placed at the end of the loop body:

LUA
for i = 1, 6 do
  if i % 2 == 0 then
    goto continue          -- skip even numbers
  end
  print(i)
  ::continue::
end
-- 1
-- 3
-- 5

A label is written between double colons. The rule that makes this work: a goto may jump to any visible label in the same block or an enclosing block, but it cannot jump into the scope of a local variable. A label at the very end of a block is exempt from that rule, which is why ::continue:: must be the last thing in the loop body. The name continue is just a convention; it is not a keyword. Use goto sparingly; this idiom and breaking out of nested loops are its two good uses.

An alternative with no goto is to invert the condition and wrap the rest of the body in an if:

LUA
for i = 1, 6 do
  if i % 2 == 1 then
    print(i)
  end
end

Loop variable scope

Variables declared inside a loop body are local to one pass of that body. The loop variable of a for is local to the loop. A variable you want to read after the loop must be declared before it:

LUA
local last
for i = 1, 3 do
  last = i * 10
end
print(last)   --> 30
-- print(i)   would print nil: i does not exist out here (it would be a global lookup)

Because i is not defined after the loop, the commented line looks up a global named i and gets nil. This is one reason to keep your code free of accidental globals, a theme in Debugging, Performance and Common Mistakes.

Try it: break and continue

This stand-in uses JavaScript's continue and break where Lua would use goto continue and break. The comments show the Lua equivalent.

JS break and continue stand-in (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many times does for i = 1, 3 do ... end run its body?

    Both ends of a numeric for are inclusive, so i takes the values 1, 2 and 3.
  2. 2. What is the difference between while and repeat ... until?

    while tests first and may run zero times. repeat tests last and stops once its condition is true.
  3. 3. How do you skip to the next iteration in Lua?

    Lua has no continue keyword. The idiom is goto to a label placed at the end of the loop body, where jumping is allowed even past local declarations.
  4. 4. What does for i = 5, 1 do print(i) end print?

    The default step is +1, so the loop cannot move from 5 toward 1 and the body never runs. Use a step of -1 to count down.

Summary

  • while cond do ... end tests first; repeat ... until cond tests last and runs at least once.
  • for i = start, stop, step do ... end is inclusive, evaluates its bounds once and gives each pass a fresh local i. A step of 0 is an error.
  • Use a negative step to count down; if the start is already past the stop, the body never runs.
  • break leaves the innermost loop.
  • There is no continue: use goto continue with ::continue:: at the end of the body.
  • Declare variables before the loop if you need them afterwards.

Continue with Iterating with pairs and ipairs.