Codectionary / Developer documentation / Lua

Lua ipairs

ipairs walks consecutive integer keys starting at 1, returning the index and value on each iteration. It stops at the first missing value (nil). Use it for a sequence such as a list of tags, rather than for a table with named keys.

Syntax

for index, tag in ipairs(tags) do
  print(index, tag)
end

Examples

Walk a sequence in order

The loop prints 1 HTML, 2 CSS and 3 Lua. ipairs supplies the index as well as the value.

local tags = { "HTML", "CSS", "Lua" }
for index, tag in ipairs(tags) do
  print(index, tag)
end

A gap stops iteration

Only 1 HTML is printed. Key 2 is missing, so ipairs never reaches key 3. A numeric loop with explicit bounds lets you handle gaps deliberately.

local tags = { [1] = "HTML", [3] = "Lua" }
for index, tag in ipairs(tags) do
  print(index, tag)
end

for index = 1, 3 do
  print(index, tags[index] or "(missing)")
end

Best practices

  • Keep sequence keys consecutive from 1 when using ipairs. A false value is visited; nil stops iteration.
  • Use pairs for named keys, but do not rely on its iteration order.
  • Do not use #table as a reliable item count for tables with gaps. Supply explicit bounds when gaps are meaningful.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading