For in Lua

Lua’s for loop is versatile and can be used in several ways. Here are some basic types of for loops in Lua.

-- The most basic type, with a single condition
i = 1
while i <= 3 do
    print(i)
    i = i + 1
end

-- A classic numeric for loop
for j = 0, 2 do
    print(j)
end

-- Lua's ipairs can be used to iterate over array-like tables
for i, _ in ipairs({0, 1, 2}) do
    print("range", i-1)
end

-- An infinite loop that breaks
while true do
    print("loop")
    break
end

-- Using continue (Lua 5.2+ with goto)
for n = 0, 5 do
    if n % 2 == 0 then
        goto continue
    end
    print(n)
    ::continue::
end

When you run this script, you’ll see:

$ lua for.lua
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Lua, the for loop can be used in two main ways:

  1. Numeric for: Used when you know the number of iterations in advance.
  2. Generic for: Used with iterator functions like pairs or ipairs to traverse tables.

The while loop in Lua is equivalent to the condition-only for loop in some other languages. Lua doesn’t have a built-in continue statement, but in Lua 5.2 and later, you can simulate it using goto.

We’ll see some other loop forms later when we look at iterators, coroutines, and other data structures.