IPairs

From Pico-8 Wiki
Jump to navigation Jump to search

New in PICO-8 0.2.0.

ipairs( tbl )
Returns an iterator of index-value pairs for all elements in a table, for use with for...in.
tbl
The table.

The ipairs() iterator function is used exclusively with for...in to iterate over all elements in the indexed sequence (array-like) portion of the table. It emits the index and value together, which you can assign to variables in the for loop:

for i, v in ipairs(tbl) do
  -- ...
end

This iterator produces only the values in the table which are considered part of its indexed sequence. It will not produce values associated with non-numeric keys, and it will not produce values for any indices greater than #table.

It is guaranteed that the indices will be produced in ascending order.

Examples

t = {111, 222, 333}
for i, v in ipairs(t) do
  print(i..': '..v)
end
-- 1: 111
-- 2: 222
-- 3: 333

t = {123, 456, n=42, x=100, y=200}
for i, v in ipairs(t) do
  print(i..': '..v)
end
-- 1: 123
-- 2: 456

See also