Lua - InBuilt Iterators



Iterator is a construct that enables you to traverse through the elements of the so called collection or container. In Lua, these collections often refer to tables, which are used to create various data structures like array. We typically uses functions to create iterators. Each time an iterator function is called, it returns the next element of the collection.

Inbuilt Iterators

Lua provides two main iterators by default.

  • ipairs()− this iterator extracts the index and is useful where table is without keys.

  • pairs()− this iterator uses the keys of table along with values.

Another option is using next() function, which is primary function to get next key-value from a collection.

Example - Using ipairs iterator with table

In following example, we've created an table of strings and using generic for with ipairs() iterator. We're printing the index and corresponding value of the collection.

main.lua

-- Initialize a table
array = {"Lua", "Tutorial"}

-- loop through table elements and print them
for index,value in ipairs(array) 
do
   print(index, value)
end

Output

When we run the above program, we will get the following output−

1	Lua
2	Tutorial

Example - Using pairs iterator with table with keys

In following example, we've created an array of strings and using generic for with pairs() iterator. pairs iterator returns next key and value pair as shown below:

main.lua

-- Initialize an array
array = {}
array["A"] = "Lua"
array["B"] = "Tutorials"

-- loop through array elements and print them
for key,value in pairs(array) 
do
   print(key, value)
end

Output

When we run the above program, we will get the following output−

A	Lua
B	Tutorial

Example - Using next function with table with keys

In following example, we've created an array of strings and using generic for with next function. next function returns next key and value pair as shown below:

main.lua

-- Initialize an array
array = {}
array["A"] = "Lua"
array["B"] = "Tutorials"

-- loop through array elements and print them
for key,value in next, array
do
   print(key, value)
end

Output

When we run the above program, we will get the following output−

A	Lua
B	Tutorial
Advertisements