Lua - Resizing Arrays



Array is an 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, array is a dynamic structure and is 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.

Size of an array can be retrieved easily using # operator.

-- print the size of the array
print(#array)

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

-- print the size of the array
print(#array)

Output

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

nil
Lua
Tutorial
2

Example - Resizing Array

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. We can add more elements to the array and it is resized automatically.

main.lua

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

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

-- print the size of the array
print(#array)

-- add more elements to the array
array[3] = "Easy"

-- print the size of the resized array
print(#array)

Output

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

nil
Lua
Tutorial
2
3
Advertisements