LuLua · Lesson 3 of 8

Tables — The Only Data Structure

Lua has exactly one data structure: the table. It's an array, a dictionary, an object, and a module all at once. Understand tables and you understand Lua.

Lua
-- As an array (1-indexed!):
local fruits = { "apple", "banana", "cherry" }
print(fruits[1])          -- apple  (NOT fruits[0])
print(#fruits)            -- 3
table.insert(fruits, "date")          -- append
table.insert(fruits, 1, "avocado")    -- insert at front
table.remove(fruits, 2)               -- remove by index
table.sort(fruits)

-- Iterate an array:
for i, fruit in ipairs(fruits) do
  print(i, fruit)
end
Lua
-- As a dictionary:
local student = {
  name = "Ada",
  age = 17,
  grade = 95,
}
print(student.name)        -- dot access
print(student["name"])     -- same thing
student.email = "ada@example.com"   -- add a key
student.age = nil                   -- delete a key

-- Iterate a dictionary:
for key, value in pairs(student) do
  print(key, value)
end

-- Nesting is free:
local party = {
  members = {
    { name = "Ada",  hp = 100 },
    { name = "Alan", hp = 85 },
  },
  gold = 250,
}
print(party.members[2].name)   -- Alan
◆ Note
ipairs walks 1, 2, 3... and stops at the first nil — use it for arrays. pairs visits every key in no guaranteed order — use it for dictionaries. Accessing a missing key returns nil rather than erroring.