ipairs

Iterates over a numerically keyed table

Prototype

it, t, 0 = ipairs (t)

Description

Returns an iterator function, the table t, and 0, for use in the generic "for" loop.

for i, v in ipairs (t) do
  -- process loop here (i is the key, v is the value)
end -- for
The iterator function, called repeatedly, returns the key and value pairs for each table item, starting at 1, until it finds the first missing integer key. For example, if keys 1 to 8 are present, and key 9 is nil, it will return the first 8 values. This occurs even if key 10 is present.

In other words, you cannot use ipairs to iterate over a table with "holes" in the key ranges.

If the table has non-numeric keys, there are gaps in the key sequence, or keys do not start at 1, then you need to use pairs (instead of ipairs) to access every item in the table (however this access will not necessarily be in numeric sequence).

Most usually you simply use ipairs to traverse a numerically-keyed table, for example:

t = {
    "the",
    "quick",
    "brown",
    "dog",
   }

for key, value in ipairs (t) do
  print (key, value)
end -- for
Example output:

1 the
2 quick
3 brown
4 dog
In this case the keys (automatically assigned) were 1, 2, 3, 4, and the values were the words in the table.

Lua functions

Topics