How do arrays work in Lua?

In Lua, an array is an arrangement of data.

Note: Due to the fact that Lua is dynamically typed, it allows different types inside the same array.

Inizialize an array

One-dimensional array

We can initialize an array with {}, as shown below:

array = {}

Multi-dimensional array

Lua also supports multi-dimensional arrays; we just need to initialize it. For example:

array = {} -- an empty array
array[1] = {} -- the second element is also a nested array

Note: Every element in an array is indexed with an integer.

Code

One-dimensional array

Let’s look at how to read and write into a one-dimensional array:

-- inizialize an array
array = {}
-- write into it
array[0] = "Hello,"
array[1] = "Educative!"
-- print elements
print(array[0], array[1])

Expected output

Hello, Educative!

Multi-dimensional array

When we need to work with multi-dimensional arrays, we need to initialize every nested array and access the numeric index in each row.

-- inizialize an array and add a nested array as second element
marray = {}
marray[1] = {}
-- add some data
marray[0] = "Hello, "
marray[1][0] = "Educative!"
marray[1][1] = "Dario!"
-- print some element
print(marray[0], marray[1][0])
print(marray[1][1])

Expected output

Hello, Educative!
Dario!

Array indexing

In Lua, the index of an array starts from 1 by default. Accessing other indexes will return nil.

-- inizialize an array
array1 = {"Hello,", "Educative!"}
-- print elements
print(array1[0], array1[1], array1[2])

Expected output

nil,  Hello,  Educative!

We can also start an array from any index value e.g. 0, 1, -3, or any other value.

-- inizialize another array
array2 = {}
-- write into it
array2[-3] = "Hello,"
array2[-2] = "Welcome"
array2[-1] = "to"
array2[0] = "the"
array2[1] = "Educative!"
-- print elements
for i = -3, 1 do
print(array2[i])
end

Expected output

Hello, 
Welcome
to
the
Educative!

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved