Lua Tables — Arrays and Dictionaries

Tables are Lua's only data structure — they serve as arrays, dictionaries, objects, and more. Every other language has separate types for these; Lua has one powerful type that does it all.

Arrays (Sequential Tables)

LUA
-- Lua arrays are 1-indexed (not 0-indexed!)
local fruits = {"apple", "banana", "mango"}

print(fruits[1])      -- "apple" (first element)
print(#fruits)        -- 3 (length operator)
print(fruits[#fruits]) -- "mango" (last element)

-- Iterating with ipairs (integer pairs — preserves order)
for i, fruit in ipairs(fruits) do
    print(i, fruit)
end
-- 1    apple
-- 2    banana
-- 3    mango

Dictionaries (Key-Value Tables)

LUA
local student = {
    name = "Sita",
    age = 21,
    grade = "A",
    courses = {"Math", "CS", "English"}
}

print(student.name)          -- "Sita"
print(student["age"])        -- 21 (bracket notation also works)
print(student.courses[1])    -- "Math"

-- Iterating with pairs (all key-value pairs — order not guaranteed)
for key, value in pairs(student) do
    print(key, value)
end

-- Adding new keys
student.email = "sita@example.com"

-- Removing a key
student.grade = nil

When to Use ipairs vs pairs

Function Use when Order
ipairs Array-like tables (sequential integer keys) Guaranteed order
pairs Dictionary-like tables (arbitrary keys) Not guaranteed

Modifying Arrays

LUA
table.insert(fruits, "orange")          -- append to end
table.insert(fruits, 2, "kiwi")         -- insert at index 2
table.remove(fruits, 1)                 -- remove first element
table.sort(fruits)                      -- sort alphabetically
table.sort(fruits, function(a, b) return a > b end)  -- reverse sort

Nested Tables

LUA
local school = {
    name = "Kathmandu Academy",
    students = {
        {name = "Ram", grade = "A"},
        {name = "Sita", grade = "B"},
        {name = "Hari", grade = "A"}
    }
}

print(school.students[1].name)  -- "Ram"

for _, student in ipairs(school.students) do
    print(student.name, student.grade)
end

Tips

  • Lua arrays start at 1, not 0 — this catches many developers off guard.
  • Use ipairs for arrays, pairs for dictionaries.
  • Tables are references — assigning a table to a new variable doesn't copy it.
  • Use #table to get the length of a sequential table.

Next: control-flow.