The Lua standard library provides a pairs
function which iterates over the keys and values of a table. When iterating with pairs
there is no specified order for traversal, even if the keys of the table are numeric.
for key, value in pairs(input_table) do
print(key, " -- ", value)
end
For tables using numeric keys, Lua provides an ipairs
function. The ipairs
function will always iterate from table[1]
, table[2]
, etc. until the first nil
value is found.
for index, value in ipairs(numeric_table) do
print(index, ". ", value)
end
Be warned that iteration using ipairs()
will not work as you might want on few occasions:
input_table
has "holes" in it. (See the section on "Avoiding gaps in tables used as arrays" for more information.) For example:
table_with_holes = {[1] = "value_1", [3] = "value_3"}
keys weren't all numeric. For example:
mixed_table = {[1] = "value_1", ["not_numeric_index"] = "value_2"}
Of course, the following also works for a table that is a proper sequence:
for i = 1, #numeric_table do
print(i, ". ", numeric_table[i])
end
Iterating a numeric table in reverse order is easy:
for i = #numeric_table, 1, -1 do
print(i, ". ", numeric_table[i])
end
A final way to iterate over tables is to use the next
selector in a generic for
loop. Like pairs
there is no specified order for traversal. (The pairs
method uses next
internally. So using next
is essentially a more manual version of pairs
. See pairs
in Lua's reference manual and next
in Lua's reference manual for more details.)
for key, value in next, input_table do
print(key, value)
end