Lua Tables

Use one table type as both an array and a record.

Lua
local scores = {82, 91, 76}
table.insert(scores, 95)
print(#scores .. " " .. scores[1])
local person = {name = "Ada", age = 36}
person.age = person.age + 1
print(person.name .. " " .. person.age)
Output
4 82
Ada 37

Explanation

Table is Lua's only data structure. With values in braces it acts as an array, and by convention the first index is 1, not 0. table.insert adds to the end and the # operator gives the length.

With names it acts as a record: person.name is shorthand for person["name"]. The concatenation operator .. joins values into a string, and numbers are converted automatically.

Explore the dry run
Guided walkthroughReady
1local scores = {82, 91, 76}
2table.insert(scores, 95)
3print(#scores .. " " .. scores[1])
4local person = {name = "Ada", age = 36}
5person.age = person.age + 1
6print(person.name .. " " .. person.age)

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
An array-style table; the first element is scores[1].scores = {82, 91, 76}
—
Append at the end.scores = {82, 91, 76, 95}
—
Length 4 and first element 82.scores = {82, 91, 76, 95}
4 82
Update a field.person.age = 37
4 82
Join the name and age.person.age = 37
4 82
Ada 37

Cost and common mistakes

Index access is O(1); table.insert at the end is amortized O(1).

  • Lua indexes start at 1, so scores[0] is nil.
  • A missing key returns nil rather than an error.

Try it yourself

What does scores[#scores] return after the insert?

Reveal answer and reasoning

The last element, 95.

Further reading