Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lua
communitycreator
array

How do arrays work in Lua?

Dario Vincenzo Tarantini

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 inizialize it. For example:

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

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])

Expected output

Hello, Educative!

RELATED TAGS

lua
communitycreator
array

CONTRIBUTOR

Dario Vincenzo Tarantini
RELATED COURSES

View all Courses

Keep Exploring