← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 1 of 7

Metatables

A metatable is a table of special rules that changes how another table behaves.

In this page:

  1. Metatables

Metatables

Every table can have a metatable, set with setmetatable(t, mt) and read with getmetatable(t). The metatable holds metamethods, fields whose names start with two underscores, such as __index and __add. Lua looks them up when an operation is not defined for the table. setmetatable returns its first argument, so it can be used in an expression.

Note: Strings share a metatable whose __index is the string table, which is why s:upper() works.

Example: Metatables

lua
local t = {}
print(getmetatable(t))
local mt = {}
local same = setmetatable(t, mt)
print(same == t, getmetatable(t) == mt)
print(getmetatable("abc").__index == string)

-- Output:
-- nil
-- true	true
-- true
Common Mistakes
  1. Forgetting that setmetatable returns the table
  2. Putting metamethod names in the table itself instead of its metatable
  3. Assuming plain tables have metatables by default
Chapter Summary
  • setmetatable attaches a metatable
  • getmetatable reads it
  • Metamethods start with __
  • Plain tables have no metatable
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.