Lua: Arrays
Arrays are like normal variables, but they can hold many pieces of data (many values).
For example lets say we wanted to store how much pupils got (out of 50) in a test, before we would have had to create a variable for each pupil but with arrays we can hold all of the pupils scores in one array!
You can declare an array like this:
ArrayOne={}
And then assign the pieces manually like this:
ArrayOne[1]=12; ArrayOne[2]=32;
In the above example we set piece one to 12, and piece two to 32.
However this is very time consuming, and there is a much quicker way!
We can assign values when we create the array:
ScoresInTest = {12, 33, 2, 44, 42, 23, 49}
In the above example piece one is 12, piece two is 33, piece three is 2 etc..
We can then access the pieces like we were when we assigned them manually:
print(ScoresInTest[1])
We can also edit values we have already assigned, and add new pieces to the array using similar methods to the manual assigning.
Here is an example program that uses arrays:
ScoresInTest = {12, 33, 2, 44, 42, 23, 49} --Creates a new array with 7 pieces called 'ScoresInTest'.
ScoresInTest[8] = 25 --Create a new piece, piece 8.
ScoresInTest[7] =32 --Change piece 7 from 49 to 32.
print(ScoresInTest[8]) --Print piece 8.
print(ScoresInTest[7]) --Print piece 7.
Arrays are in fact simply a type of table in lua, so we can use the arrays we just created as stacks, queues, vectors, and more, as well as just arrays.
A typical example of array use is outputting all of the values in an array (using a for loop):
array = {1,2,3,4,5}
for i = 1, #array do
print(a[i])
end
Note that "#array" means the program should get the length of the array (in other words how many values are in the array).
You can delete certain array entries by setting them to nil:
array = {}
x = "Hi"
array[x] = 10
print(array[x])
array[x] = nil
All we did above is create an array with a key (the thing we find the bit of data in the array by (the thing in the square brackets)) of a string (Hi, in our case); Then we set piece "Hi" to 10, next we printer piece "Hi" (10), and then we deleted piece "Hi" by setting it to nil.
With some nesting of arrays we can create more complicated tables, like so:
employees = {company = "Youtube", department = "Webmaster"},
{name = "Fred Savage", age = 21},
{name = "Bob Smith", age = 43},
{name = "Laura Brown", age = 27}
}
print(employees.company .. "'s " .. employees.department .. " department employees: ")
for i = 1, #employees do
print(employees[i].name .. " " .. employees[i].age)
end
Note that the string concatenation is '..' rather then the usual '+' or ','.
Back to Lua

