Lua Standard Iterators


Example

The Lua standard library provides two iterator functions that can be used with a for loop to traverse key-value pairs within tables.

To iterate over a sequence table we can use the library function ipairs.

for index, value in ipairs {'a', 'b', 'c', 'd', 'e'} do
  print(index, value)  --> 1 a, 2 b, 3 c, 4 d, 5 e
end

To iterator over all keys and values in any table we can use the library function pairs.

for key, value in pairs {a=1, b=2, c=3, d=4, e=5} do
  print(key, value)  --> e 5, c 3, a 1, b 2, d 4  (order not specified)
end