TExcelTAD
Home › Lua › Lua Metatables

Lua Metatables

Every table can have a metatable: a second, ordinary table that changes how the first one behaves. When Lua hits an operation that a table doesn't support on its own (adding it with +, reading a missing key, calling it like a function), it looks in the metatable for a special field called a metamethod, such as __add or __index.

lua · try it yourself
local mt = {}
local t = setmetatable({}, mt)     -- setmetatable returns its first argument

print(getmetatable(t) == mt)
print(getmetatable({}))            -- plain tables have no metatable
print(getmetatable("text").__index == string)
true
nil
true

The last line shows why ("text"):upper() works: all strings share a metatable whose __index is the string table.

__index: defaults for missing keys

When you read a key that is not present in a table, Lua checks the metatable's __index. If it is a table, the key is looked up there:

lua · try it yourself
local defaults = { colour = "grey", size = "M", stock = 0 }
local shirt = setmetatable({ colour = "navy" }, { __index = defaults })

print(shirt.colour)    -- found in shirt itself
print(shirt.size)      -- missing: taken from defaults
print(shirt.price)     -- missing in both: nil
print(rawget(shirt, "size"))  -- rawget skips the metatable
navy
M
nil
nil

__index can also be a function (table, key), called for every missing key:

lua · try it yourself
local squares = setmetatable({}, {
  __index = function(t, n)
    local value = n * n
    rawset(t, n, value)        -- cache it for next time
    return value
  end,
})

print(squares[7], squares[12])
print(rawget(squares, 7))      -- now really stored
49	144
49

__newindex: controlling assignments

__newindex runs when you assign to a key that is not already present. Use it to validate, log or redirect writes:

lua · try it yourself
local function strictRecord(fields)
  local allowed = {}
  for _, f in ipairs(fields) do allowed[f] = true end
  return setmetatable({}, {
    __newindex = function(t, key, value)
      if not allowed[key] then
        error("unknown field '" .. tostring(key) .. "'", 2)
      end
      rawset(t, key, value)
    end,
  })
end

local user = strictRecord({ "name", "email" })
user.name = "Lena"
print(user.name)
print(pcall(function() user.nmae = "typo" end))
Lena
false	/app/output.s:17: unknown field 'nmae'

rawset stores the value without triggering __newindex again (which would loop forever). Level 2 in error blames the line that made the assignment rather than the metamethod.

Read-only tables

Combining an empty proxy with __index and __newindex gives a table that can be read but not changed:

lua · try it yourself
local function readOnly(t)
  return setmetatable({}, {
    __index = t,
    __newindex = function() error("attempt to modify a read-only table", 2) end,
    __len = function() return #t end,
  })
end

local DAYS = readOnly({ "Mon", "Tue", "Wed", "Thu", "Fri" })
print(DAYS[2], #DAYS)
local ok, err = pcall(function() DAYS[1] = "Sun" end)
print(ok, err)
Tue	5
false	/app/output.s:11: attempt to modify a read-only table

The raw functions

Function Does the same as … but ignores metamethods
rawget(t, k) t[k]
rawset(t, k, v) t[k] = v
rawequal(a, b) a == b
rawlen(t) #t

Protecting a metatable

If the metatable has a __metatable field, getmetatable returns that value instead, and setmetatable refuses to change it. Libraries use this to stop users from tampering with their objects:

lua · try it yourself
local obj = setmetatable({}, { __metatable = "locked" })
print(getmetatable(obj))
print(pcall(setmetatable, obj, {}))
locked
false	cannot change a protected metatable

Test yourself

When is a table's __index metamethod used?

  1. On every read
  2. When reading a key that is absent from the table
  3. When writing any key
  4. When the table is printed

Why use rawset inside a __newindex function?

  1. It is faster than =
  2. To store the value without triggering __newindex again
  3. To make the field read-only
  4. It is required by the syntax

What does setmetatable(t, mt) return?

  1. mt
  2. t
  3. true
  4. Nothing