Lua Arrays

In this article, we will discuss what Lua arrays are, how to create them, and how to use them effectively.

Lua Arrays are collections of elements, usually of the same type, stored in contiguous memory locations and accessed using indexes and subscripts.

The use of arrays provides a convenient way to store and manipulate large amounts of structured data, whether they are fixed or dynamic.

Lua arrays are represented by tables and are implemented as tables with integer keys beginning with 1. The values can be of any data type, including nil.



Lua Array Creation

To create an array in Lua, you can initialize a table with values. Lua arrays are dynamic, meaning you can add or remove elements at any time.

An example of array initialization is provided below where an array ‘arr’ is initialized:

arr = {"Dell", "Lenovo", "HP", "Apple"}

Accessing Elements In An Array

In Lua, you can access array elements using the square bracket notation [].

Square brackets enclose the index of the element you want to access. In Lua, array indexes start at 1, not 0.

This code, for example, will allow us to access the second element of the arr array:

Example: 

arr = {"Dell", "Lenovo", "HP", "Apple"}print(arr[2])

Add Element To Array

Lua allows you to add new elements to arrays by assigning values to new indexes.

To accommodate the new element, Lua automatically increases the array size.

For example, to add a new element with the value “Acer” to the arr array, we can use the following code:

arr[5] = "Acer"

Let’s use the above code snippet in an example:

Example: 

arr = {"Dell", "Lenovo", "HP", "Apple"} arr[5] = "Acer" print(arr[5])

Iterate Over Array

To iterate over the elements of an array and perform operations on its elements, we can use a loop.
Here’s an example of how to use a generic for loop to iterate over the elements of the arr array:

Example: 

local arr = {"Dell", "Lenovo", "HP", "Apple"}for i=1,#arr do print(i..") "..arr[i]) end

Multidimensional Arrays

Up until now, we have seen arrays that are one-dimensional.

By using tables within tables, you can also create multidimensional arrays in Lua.

This is the syntax to creates an array with two rows and three columns in Lua:

arr = {
{2, 4, 6},
{8, 10, 12},
}

Following example prints the contents of the array defined above:

Example: 

arr = { {2, 4, 6}, {8, 10, 12}, }for i=1,2 do for j=1,3 do print(arr[i][j]) end end
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *