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.
We can initialize an array with {}
, as shown below:
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.
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])
Hello, Educative!
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])
Hello, Educative!
RELATED TAGS
CONTRIBUTOR
View all Courses