Skip to content
AgileLogics
5 min read

Arrays

Prerequisites: Tables: the one data structure

An array (or list) in Lua is a table with keys 1, 2, 3, ....

local fruits = {"apple", "banana", "cherry"}

print(fruits[1])
print(fruits[#fruits])
print(#fruits)
print(fruits[0])

fruits[#fruits + 1] = "date"
fruits[2] = "blueberry"
for i = 1, #fruits do
  print(i, fruits[i])
end
apple
cherry
3
nil
1	apple
2	blueberry
3	cherry
4	date
  • Indexes start at 1 — fruits[0] is nil.
  • #fruits is the length; fruits[#fruits + 1] = x appends.
  • Loop with a numeric for from 1 to #t, or with ipairs (next lessons).

Holes break

# is only reliable for arrays without gaps (nil values in the middle):

local t = {1, 2, 3}
t[5] = 5
print(#t == 3 or #t == 5)

local u = {1, 2, 3}
u[2] = nil
print(u[1], u[2], u[3])
true
1	nil	3

With holes, # may return any "border", so the result isn't defined. To remove an element from the middle, use table.remove, which shifts the rest down.

Arrays of tables

local people = {
  {name = "Ada", age = 36},
  {name = "Linus", age = 28},
  {name = "Grace", age = 45},
}

local total = 0
for i = 1, #people do
  total = total + people[i].age
end
print(string.format("Average age: %.1f", total / #people))
print(people[2].name)
Average age: 36.3
Linus

A trailing comma after the last element is allowed and makes adding lines easier.

Practice

Create an array of five numbers and print the largest and the total.

Show solution
local numbers = {12, 7, 31, 5, 18}
local largest, total = numbers[1], 0
for i = 1, #numbers do
  largest = math.max(largest, numbers[i])
  total = total + numbers[i]
end
print(largest, total)
31	73