Lua Arrays
As previously mentioned, tables in Lua are used to represent other structures, with arrays being one of them. An array is a special type of variable that contains multiple values of the same type. The following string variable, ‘fname’, has been defined and initialised with the name ‘Bob’.
fname = "Bob"
If multiple names need to be stored, instead of having a different variable for each, an array could be used.
fnames = {"Bob", "George", "Fred", "Alan"}
An array can also initially be defined with no values and then the table 'insert' method can be used to add values one at a time to the end of the array.
fnames = {}
table.insert(fnames, "Bob")
table.insert(fnames, "George")
table.insert(fnames, "Fred")
table.insert(fnames, "Alan")
Items in an array have an index value, with the first item having an index value of one, the second item having an index value of two, and so on. The 'insert' method, in conjunction with an index value can be used to incorporate an additional value into the specified position.
table.insert(fnames, 2, "Alice")
Here, the name 'Alice' is added in to the array at the second index position.
The index value can also be used to access a single value in an array.
fnames = {"Bob", "George", "Fred", "Alan"}
print(fnames[2])
If it is required to display all the values in an array, with each value on a separate line, then a 'for' loop can be used to achieve this.
fnames = {"Bob", "George", "Fred", "Alan"}
for i = 1, #fnames
do
print(fnames[i])
end
The '#' sign in front of the array name is used to get the length of the array and therefore indicate the number of iterations through the loop. The resulting output is shown below.
Bob George Fred Alan
Using the table 'concat' method it is also possible to display the values from an array on a single line.
fnames = {"Bob", "George", "Fred", "Alan"}
print(table.concat(fnames, ", "))
Here, the items in the array are separated by a comma and a space on a single line.
Bob, George, Fred, Alan
The values in an array can also be sorted using the table 'sort' method.
fnames = {"Bob", "George", "Fred", "Alan"}
table.sort(fnames)
print(table.concat(fnames, ", "))
The resulting output now looks as follows.
Alan, Bob, Fred, George
Finally, if it is required to remove a value from an array the table 'remove' method can be utilised.
table.remove(fnames, 2)
Here, the value with an index of two is removed from the array.