Lua - Iterating over Arrays



In Lua, we can iterate an array using pairs() and ipairs() functions. Both functions return key-value pairs where the key is the index of the element and the value is the element stored at that index in the array.

Syntax

-- loop through array using ipairs() method
for key,value in ipairs(array) do print(key,value) end
-- loop through array using pairs() method
for key,value in pairs(array) do print(key,value) end
  • key− index

  • value− value stored in the corresponding index of array

  • array− array

Example - Using pairs() method

Create a new source file named main.lua and paste the following code to iterate the array with pairs() method.

main.lua

-- initialize an array
array = {"a", "b", "c", "d", "e", "f"}

-- add a new value to the array
array["last"] = "end"

-- loop through indexes and values of array
for key,value in pairs(array) 
do
   -- print the values 
   print(key,value) 
end

Output

1	a
2	b
3	c
4	d
5	e
6	f
last	end

Example - Using ipairs() method

Create a new source file named main.lua and paste the following code to iterate the array with ipairs() method.

main.lua

-- initialize array with values
array = {"a", "b", "c", "d", "e", "f"}

-- add a new value
array["last"] = "end"

-- loop through indexes and values of array
for key,value in ipairs(array) 
do 
   -- print the key, value
   print(key,value) 
end

Output

1	a
2	b
3	c
4	d
5	e
6	f

You can notice, that if index is non-number, then ipairs is rejecting the entry.

Example - Using custom iterator

We can create our own iterator to iterate an array. Consider the following function which returns an iterator.

-- function to return a function which can iterate array
function getValues(array)
  local i = 0
  return function() i = i + 1; return array[i] end
end

We can use this function in for loop as shown below.

-- iterate using custom function
for value in getValues(array) 
do 
   -- print the value
   print(value)
end

Following is the complete code.

main.lua

-- function to return a function which can iterate array
function getValues(array)
  local i = 0
  return function() i = i + 1; return array[i] end
end

-- initialize an array with values
array = {"a", "b", "c", "d", "e", "f"}

-- iterate using custom function
for value in getValues(array) 
do 
   -- print the value
   print(value) 
end

Output

a
b
c
d
e
f
Advertisements