CodeToLive

Tables & Metatables in Lua

Tables are the only data structure mechanism in Lua, but they are so powerful that they can represent arrays, sets, records, objects, and more. Metatables allow you to define custom behavior for tables.

Basic Table Usage

Tables in Lua can be used as arrays or dictionaries:

-- Array-like table
local fruits = {"apple", "banana", "cherry"}
print(fruits[1])  -- "apple" (Lua uses 1-based indexing)

-- Dictionary-like table
local person = {
    name = "Alice",
    age = 30,
    profession = "Engineer"
}
print(person.name)  -- "Alice"

Table Operations

Common operations with tables:

local t = {}

-- Insert elements
table.insert(t, "a")  -- Insert at end
table.insert(t, 1, "b")  -- Insert at position 1

-- Remove elements
table.remove(t, 1)  -- Remove element at position 1

-- Get length
print(#t)  -- Length operator (works for array part)

Iterating Over Tables

Different ways to iterate through tables:

-- Array-style iteration
local colors = {"red", "green", "blue"}
for i, color in ipairs(colors) do
    print(i, color)
end

-- Dictionary-style iteration
local config = {width=800, height=600, fullscreen=false}
for key, value in pairs(config) do
    print(key, value)
end

Metatables

Metatables allow you to define custom behavior for tables:

local t1 = {1, 2, 3}
local t2 = {4, 5, 6}

-- Create a metatable with __add metamethod
local mt = {
    __add = function(a, b)
        local result = {}
        for i, v in ipairs(a) do
            table.insert(result, v + b[i])
        end
        return result
    end
}

setmetatable(t1, mt)
setmetatable(t2, mt)

local sum = t1 + t2  -- {5, 7, 9}

Common Metamethods

Some useful metamethods:

  • __index - controls table lookup
  • __newindex - controls table updates
  • __add, __sub, etc. - operator overloading
  • __call - makes a table callable like a function
  • __tostring - controls string representation

Object-Oriented Programming

Tables with metatables can implement OOP concepts:

-- Simple class implementation
local Person = {}

function Person:new(name, age)
    local obj = {
        name = name,
        age = age
    }
    setmetatable(obj, {__index = Person})
    return obj
end

function Person:greet()
    return "Hello, my name is " .. self.name
end

local alice = Person:new("Alice", 30)
print(alice:greet())

Next Steps

Now that you understand tables and metatables, learn about modules and packages in Lua.