Lua - Arrays



Arrays are ordered arrangement of objects, which may be a one-dimensional array containing a collection of rows or a multi-dimensional array containing multiple rows and columns.

In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

Example - Create Array

An array can be represented using a simple table structure and can be initialized and read using a simple for loop. An example is shown below.

main.lua

-- initialize an array
array = {"Lua", "Tutorial"}

-- iterate the array and print values
for i = 0, 2 do
   print(array[i])
end

Output

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

nil
Lua
Tutorial

Example - Array with Negative Indexes

As you can see in the above code, when we are trying to access an element in an index that is not there in the array, it returns nil. In Lua, indexing generally starts at index 1. But it is possible to create objects at index 0 and below 0 as well. Array using negative indices is shown below where we initialize the array using a for loop.

main.lua

-- create an empty array
array = {}

-- initialize array with negative indexes
for i= -2, 2 do
   array[i] = i *2
end

-- iterate elements of array and print
for i = -2,2 do
   print(array[i])
end

Output

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

-4
-2
0
2
4
Advertisements