🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Tables

A table is a container that holds values in numbered or named slots. Almost every group of values in Lua is stored in a table.

Slots start at 1

This table holds three numbers in order. The prints read the first and third slots.

local t = {10, 20, 30}
print(t[1])
print(t[3])

Named slots hold details

A field stores a value under a name. The name can be read with a dot or with brackets.

local person = {name = "Sam", age = 12}
print(person.name)
print(person["name"])
print(person.age)

A slot can be changed

Assigning a new value to a slot replaces the old one. The other slots stay the same.

local t = {10, 20, 30}
t[2] = 99
print(t[1])
print(t[2])
print(t[3])

Example

local basket = {"bread", "milk", "eggs"}
local prices = {2, 3, 4}
print(basket[1])
print(basket[2])
print(basket[3])
print(prices[1] + prices[2] + prices[3])

Key points

  • Table: A table holds a group of values in one variable.
  • Constructor: Curly braces { } build a new table.
  • Array slot: A numbered slot holds one value from the list.
  • Field: A named slot such as name holds a value under that name.
  • Access: Write t[1] for a numbered slot or t.name for a named slot.
  • Change: Assigning to a slot replaces the value stored there.

In this example, basket holds three item names in numbered slots and prices holds their prices in matching slots. The first three prints read the items in order. The last print adds the three prices and shows the total 9.

Note

Lua counts array slots from 1, not from 0 like many other languages.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does print(t[1]) show when local t = {7, 8, 9}?