A Lua for loop comes in two forms: the numeric for i = 1, 10 do ... end, which counts from a start value to a limit, and the generic for k, v in pairs(t) do ... end, which walks the values an iterator function returns. Use the numeric form for counting and for arrays, and the generic form for tables, strings and custom iterators.
for i = 1, 3 do
print(i)
end
for index, value in ipairs({"a", "b", "c"}) do
print(index, value)
end
The examples below follow the Lua 5.4 reference manual. Where Lua 5.1, 5.2, 5.3 or LuaJIT differ, the text says so or stays silent about the difference.
Numeric for loop syntax
The numeric loop has this shape:
for var = start, limit, step do
-- body
end
The step is optional and defaults to 1. The loop variable var is a new local that exists only inside the body. The three expressions are evaluated once, before the first iteration. If you write for i = 1, f(x) do, the function f is called one time, not once per pass.
for i = 1, 5 do
print(i)
end
-- example output: 1 2 3 4 5, one per line
The limit is inclusive. The loop continues while the value is less than or equal to the limit, so the example above prints 5 as well. If the start value is already past the limit, the body never runs and there is no error.
Count down or skip values with a step
A negative step makes the sequence decrease. In that case the loop continues while the value is greater than or equal to the limit.
for i = 10, 1, -3 do
print(i)
end
-- example output: 10 7 4 1
A step of zero raises an error, so if the step comes from a variable, make sure it cannot be zero. Counting down without the negative step does nothing at all, because for i = 10, 1 do starts past the limit and runs zero times. This is one of the most common beginner mistakes.
Integers and floats in a numeric loop
If the start value and the step are both integers, the loop runs with integers, and the limit is allowed to be a non-integer. Otherwise all three values are converted to floats. The manual warns about floating-point accuracy in that case.
for i = 1, 3.5 do
print(i)
end
-- example output: 1 2 3
for x = 0, 1, 0.25 do
print(x)
end
-- example output: 0.0 0.25 0.5 0.75 1.0
In an integer loop the control variable never wraps around. If the next value would overflow, the loop ends instead. With float steps such as 0.1, repeated addition may leave you a hair away from the limit, so the last value you expect might not appear. When exact counts matter, loop over an integer and compute the float inside the body: for n = 0, 10 do local x = n / 10 ... end.
The loop variable is local to the loop
After the loop ends, the control variable is gone. Reading it afterwards looks up a global with that name.
for i = 1, 10 do
print(i)
end
print(i) -- nil: this is a global named i, not the loop variable
To keep a value, copy it to a variable declared outside the loop before you leave. This is the pattern for "find the first match":
local items = {"red", "green", "blue"}
local found = nil
for i = 1, #items do
if items[i] == "green" then
found = i
break
end
end
print(found) -- 2
The manual also says not to assign to the control variable inside the body. Programming in Lua describes the result of doing so as unpredictable. Use break to stop early, which ends the innermost enclosing loop.
Generic for loop syntax
The generic loop has this shape:
for name1, name2 in explist do
-- body
end
Lua evaluates explist once and gets four values: an iterator function, a state, an initial value for the control variable, and a closing value. On every iteration Lua calls the iterator function with the state and the current control variable, and assigns the results to your loop variables. The first loop variable is the control variable, and the loop ends when it becomes nil. The closing value acts like a to-be-closed variable, so it can release a resource when the loop ends. In everyday code you rarely write these four values yourself, because pairs, ipairs and string.gmatch produce them for you.
Loop over an array with ipairs
ipairs(t) visits t[1], t[2], and so on, up to the first absent index. It stops at the first nil, so a hole in the array ends the loop early.
local fruits = {"apple", "banana", "cherry"}
for index, name in ipairs(fruits) do
print(index, name)
end
-- example output:
-- 1 apple
-- 2 banana
-- 3 cherry
local sparse = {"a", "b", nil, "d"}
for index, value in ipairs(sparse) do
print(index, value)
end
-- example output: only 1 a and 2 b, because index 3 is absent
If your array may contain holes, use a numeric loop with an explicit length instead, for example for i = 1, n do where you track n yourself. The length operator # is not reliable for tables with holes.
Loop over a table with pairs
pairs(t) returns the next function, the table and nil, so the loop visits every key-value pair. If the table has a __pairs metamethod, pairs calls it and returns its first three results instead.
local ages = { alice = 31, bob = 27 }
for name, age in pairs(ages) do
print(name, age)
end
-- example output (order may differ):
-- alice 31
-- bob 27
The manual states that the order in which indices are enumerated is not specified, even for numeric indices. If you need the elements in order, use a numeric for over the indices, or collect the keys, sort them with table.sort, and loop over the sorted list.
Changing a table while you loop over it
Per the manual's entry for next, you should not assign a value to a non-existent field during traversal. You may modify existing fields, and in particular you may set existing fields to nil. So removing entries inside a pairs loop is allowed:
for key, value in pairs(ages) do
if value < 30 then
ages[key] = nil -- allowed: the field already exists
end
end
Adding new keys inside the same loop is not allowed, and the behavior is undefined.
Loop over the words in a string with gmatch
string.gmatch(s, pattern) returns an iterator function that gives the next captures of the pattern each time it is called, which fits the generic loop directly.
for word in string.gmatch("one two three", "%a+") do
print(word)
end
-- example output: one, two, three on separate lines
One detail from the manual: a caret ^ at the start of the pattern does not work as an anchor in gmatch, because that would stop the iteration.
How to write continue in a Lua for loop
Lua has no continue keyword. Since Lua 5.2 you can use goto with a label at the end of the body:
for i = 1, 10 do
if i % 2 == 0 then
goto continue
end
print(i)
::continue::
end
-- example output: 1 3 5 7 9
Two rules from the manual matter here. A label is visible in the entire block where it is defined, except inside nested functions. And a goto can jump to any visible label as long as it does not enter the scope of a local variable. If you declare a local after the goto and before the label, the jump would enter that local's scope. Lua allows it when the label is at the very end of the block, as above, because void statements after the label do not count. If you need code after the label, wrap the middle of the body in do ... end. An alternative that avoids goto is to invert the condition and put the rest of the body inside an if.
Common mistakes
- Counting down without a step.
for i = 10, 1 doruns zero times. Writefor i = 10, 1, -1 do. - Using the loop variable after the loop. It is local to the loop, so the name afterwards is an unrelated global.
- Expecting
pairsto return items in order. The order is unspecified. Useipairsor a numeric loop for arrays. - Using
ipairson a table with holes. It stops at the first absent index. - Adding keys during a
pairsloop. Only changing or clearing existing fields is allowed. - Reassigning the control variable. Assigning to it inside the body does not behave the way it does in some other languages. Copy it to a new local first.
Which loop to use
| Goal | Loop |
|---|---|
| Repeat a fixed number of times | for i = 1, n do |
| Count down | for i = n, 1, -1 do |
| Walk an array in order | for i, v in ipairs(t) do |
| Visit every key and value | for k, v in pairs(t) do |
| Split text by a pattern | for w in string.gmatch(s, pattern) do |
When no for loop fits, for example when the number of passes depends on a condition that changes inside the body, Lua also has while and repeat ... until, which the same manual section covers.
Frequently asked questions
- Does a Lua for loop include the last value?
- Yes. A numeric for loop runs while the control variable is less than or equal to the limit (or greater than or equal to it when the step is negative). So for i = 1, 3 runs for 1, 2 and 3.
- Does Lua have a continue statement?
- No. The usual replacement is goto continue with a label ::continue:: at the end of the loop body. A label is visible in the whole block where it is defined, and a goto may not jump into the scope of a local variable.
- What is the difference between pairs and ipairs in Lua?
- ipairs walks the keys 1, 2, 3 and so on in order and stops at the first absent index. pairs visits every key-value pair of the table, including string keys, and the order is not specified.
- Can I change the loop variable inside a Lua for loop?
- You should not. The Lua manual says not to assign to the control variable of a numeric or generic for loop. If you need to stop early, use break, and copy the value to another variable first if you need it after the loop.
- Is the loop variable available after the loop ends?
- No. The control variable is a new local that exists only inside the loop body. Reading it after the loop refers to a global variable of the same name, which is usually nil.