Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 32 ยท Metatables and OOP

Metatables and Metamethods

Understand Lua metatables: setmetatable, __index and __newindex for lookups and writes, arithmetic and comparison metamethods, __tostring, __call and __len.

A plain Lua table can store values, but it cannot do much on its own. You cannot add two tables with +, print one in a readable way, or give missing keys a default. Metatables change that. A metatable is an ordinary table of special functions and values, attached to another table, that tells Lua what to do in situations the table would otherwise reject or answer with nil.

The special keys all start with two underscores and are called metamethods: __index, __newindex, __add, __tostring, and so on. Metatables are the foundation of everything in Lua that looks like object-oriented programming, which the next two lessons build on.

A metatable is a rulebook

The table Holds your data.
Its metatable Holds special rules.
setmetatable Connects the two.

Lua checks the rulebook when normal behavior fails.

1 / 2

The live editors in this lesson are JavaScript stand-ins, mostly built on Proxy. They model the behavior but are not Lua. The Lua snippets are read-only.

setmetatable and getmetatable

setmetatable(t, mt) attaches mt to t and returns t, so you can write the call inline. getmetatable(t) returns the metatable, or nil:

LUA
local mt = {}
local t = setmetatable({}, mt)
print(getmetatable(t) == mt)    --> true

A table has at most one metatable, and a metatable is itself just a table, so it can be shared by many tables. Only tables can have individual metatables from Lua code; all strings share one built-in metatable, which is why ("abc"):upper() works (see Strings).

__index: reading missing keys

When you read t[k] and k is absent, Lua looks for __index in the metatable. If it is a table, Lua repeats the lookup in that table. If it is a function, Lua calls it with (t, k) and uses the result:

LUA
local defaults = {color = "blue", size = 10}
local widget = setmetatable({size = 20}, {__index = defaults})

print(widget.size)              --> 20    (found in widget itself)
print(widget.color)             --> blue  (found through __index)
print(widget.weight)            --> nil   (nowhere)

local counter = setmetatable({}, {
  __index = function(t, key) return #key end,
})
print(counter.banana)           --> 6

Own fields always win; __index is only a fallback. The lookup chain can be several tables long, which is how inheritance works. If you need to read a key without triggering metamethods, use rawget(t, k).

JS Stand-in: __index with a table and a function

Press Run (or Ctrl + Enter) to see the console output here.

No output.

__newindex: writing new keys

__newindex is consulted when you assign to a key that does not exist yet in the table. Existing keys are assigned directly. As a table it redirects the write; as a function it receives (t, k, v). Inside it, use rawset(t, k, v) to store a value without re-triggering the metamethod:

LUA
local locked = setmetatable({}, {
  __newindex = function(t, k, v)
    error("cannot add field '" .. tostring(k) .. "'", 2)
  end,
})
-- locked.x = 1   --> error: cannot add field 'x'

A common use is catching typos: a table that rejects unknown names turns silent mistakes into immediate errors.

Arithmetic and concatenation metamethods

Defining __add, __sub, __mul, __div, __mod, __unm (negation), __concat and friends lets your tables take part in expressions. Lua checks the left operand first, then the right:

LUA
local Vec = {}
Vec.__index = Vec

local function vec(x, y) return setmetatable({x = x, y = y}, Vec) end

Vec.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
Vec.__tostring = function(v) return "(" .. v.x .. ", " .. v.y .. ")" end

local sum = vec(1, 2) + vec(10, 20)
print(sum)                      --> (11, 22)

__tostring is used by tostring and therefore by print. Without it, printing a table shows something like table: 0x..., an address that differs from run to run.

Comparison metamethods

  • __eq runs for == and ~= only when both operands are tables (or both userdata) that are not the very same object. Raw identity is checked first.
  • __lt handles < (and >, by swapping operands).
  • __le handles <= and >=. Lua 5.4 removed the old rule that derived it from __lt (some builds keep it as a compatibility option), so define __le yourself if you need it.

The result of these metamethods is converted to a boolean. Comparing two values of different types with < still raises an error, and __eq is never called for a table versus a number.

JS Stand-in: vectors with +, == and a readable print

Press Run (or Ctrl + Enter) to see the console output here.

No output.

__call and __len

__call makes a table callable like a function. The metamethod receives the table first, then the call's arguments:

LUA
local greeter = setmetatable({greeting = "Hello"}, {
  __call = function(self, name) return self.greeting .. ", " .. name end,
})
print(greeter("Ada"))           --> Hello, Ada

__len customizes the # operator for tables. It is useful when a table wraps other storage, though plain # on a sequence is faster:

LUA
local ticket = setmetatable({}, {__len = function() return 42 end})
print(#ticket)                  --> 42
JS Stand-in: callable and length-aware tables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Protecting and inspecting metatables

If the metatable has a __metatable field, getmetatable returns that value instead of the real metatable, and setmetatable refuses to change it. This is a simple way to keep library objects from being tampered with. rawget, rawset, rawequal and rawlen always bypass metamethods, which is helpful inside the metamethods themselves.

Next you will use these tools to build classes in Objects and Classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is the __index metamethod used?

    Own fields always win. __index is consulted only as a fallback when the key is absent.
  2. 2. What does setmetatable(t, mt) return?

    It returns the table t, which is why you can write setmetatable({}, mt) inline.
  3. 3. Which function writes a value into a table without triggering __newindex?

    rawset bypasses metamethods, so it is the safe way to store a value from inside an __newindex handler.
  4. 4. Which metamethod makes print(obj) show a readable string?

    tostring (used by print) calls __tostring when it is defined. Otherwise you see an address like table: 0x...

Summary

  • setmetatable(t, mt) attaches rules to t and returns t; getmetatable reads them.
  • __index supplies fallbacks for missing reads (a table or a function); __newindex intercepts writes to new keys; rawget/rawset bypass them.
  • __add, __sub, __concat, __eq, __lt, __le and others let tables work with operators. define __le yourself rather than relying on __lt.
  • __tostring controls printing, __call makes a table callable, __len customizes #.
  • __metatable locks a metatable against inspection and replacement.

Continue with Objects and Classes.