Lua - Table Iterators



Table is special data structure in Lua which can be used to create different types like array or dictionaries. Lua provides three types of inbuilt iterators to navigate through table entries.

  • next− this is an inbuilt function to give the next value from the table when invoked.

  • ipairs()− this iterator uses default keys starting from 1 and is useful where table is not having any explicit keys.

  • pairs()− this iterator is useful when table is having explicit keys.

Let's see each one of the above functions to iterate values of a table.

Example - Using next function

next function accepts a table and index to return the next value of the table.

next(table, [, index])

Here next function returns the associated value from the table as per index. If index is nil, then first value is returned. Following example showcases the same−

main.lua

-- initialize array of fruits
fruits = {[2] = "banana",[4] = "orange",[6]="apple",[8] = "grapes"}

-- print the entries of table along with keys
for key,value in next,fruits do
  print(key,value)
end

Output

When the above code is built and executed, it produces the following result −

8	grapes
2	banana
4	orange
6	apple

Example - Using pairs iterator

pairs iterator function returns key-value pairs and is mainly used in associative tables. Keys are preserved but order is not preserved. See the example below−

main.lua

-- initialize array of fruits
fruits = {[2] = "banana",[4] = "orange",[6]="apple",[8] = "grapes"}

-- print the entries of table along with keys
for key,value in pairs(fruits) do
  print(key,value)
end

Output

When the above code is built and executed, it produces the following result −

8	grapes
2	banana
4	orange
6	apple

Example - Using ipairs iterator

pairs iterator function returns index-value pairs and is mainly used in tables without associative keys. See the example below−

main.lua

-- initialize array of fruits
fruits = {"banana","orange","apple","grapes"}

-- print the entries of table along with default keys
for key,value in ipairs(fruits) do
  print(key,value)
end

Output

When the above code is built and executed, it produces the following result −

1	banana
2	orange
3	apple
4	grapes
Advertisements