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 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.
Let’s look at how to read and write into a one-dimensional array:
-- inizialize an arrayarray = {}-- write into itarray[0] = "Hello,"array[1] = "Educative!"-- print elementsprint(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 elementmarray = {}marray[1] = {}-- add some datamarray[0] = "Hello, "marray[1][0] = "Educative!"marray[1][1] = "Dario!"-- print some elementprint(marray[0], marray[1][0])print(marray[1][1])
Hello, Educative!
Dario!
In Lua, the index of an array starts from 1 by default. Accessing other indexes will return nil
.
-- inizialize an arrayarray1 = {"Hello,", "Educative!"}-- print elementsprint(array1[0], array1[1], array1[2])
nil, Hello, Educative!
We can also start an array from any index value e.g. 0, 1, -3, or any other value.
-- inizialize another arrayarray2 = {}-- write into itarray2[-3] = "Hello,"array2[-2] = "Welcome"array2[-1] = "to"array2[0] = "the"array2[1] = "Educative!"-- print elementsfor i = -3, 1 doprint(array2[i])end
Hello,
Welcome
to
the
Educative!
Free Resources