Lesson 01 of 05
Metatable Fundamentals
Attach special behaviors to tables using metatables and metamethods.
Metatables attach special behaviors to tables. Every table can have a metatable set with setmetatable(table, metatable).
The metatable contains metamethods — special keys starting with __ (double underscore) that define how the table responds to operations.
Key metamethods:
- __index — handles failed key lookups (enables inheritance)
- __newindex — intercepts assignment to missing keys
- __add, __sub, __mul, __div — arithmetic operators
- __concat — .. operator
- __eq — == comparison
- __lt, __le — < and <= comparisons
- __len — # operator
- __tostring — tostring() and print() output
- __call — makes table callable like a function
- __unm — unary minus (-)
__index in detail: When a key isn't found in the table, Luau checks __index.
- If __index is a table: looks for key in that table (inheritance!)
- If __index is a function: calls function(table, key)
__metatable — setting this field hides the real metatable from getmetatable().
luau
1-- Basic metatable
2local Vector = {}
3Vector.__index = Vector
4
5function Vector.new(x, y)
6 return setmetatable({x = x, y = y}, Vector)
7)
8end
9
10-- Operator overloading
11function Vector.__add(a, b)
12 return Vector.new(a.x + b.x, a.y + b.y)
13end
14
15function Vector.__tostring(v)
16 return string.format("Vector(%g, %g)", v.x, v.y)
17end
18
19function Vector.__eq(a, b)
20 return a.x == b.x and a.y == b.y
21end
22
23function Vector:magnitude()
24 return math.sqrt(self.x^2 + self.y^2)
25end
26
27local v1 = Vector.new(3, 0)
28local v2 = Vector.new(0, 4)
29local v3 = v1 + v2 -- uses __add
30print(tostring(v3)) -- Vector(3, 4)
31print(v3:magnitude()) -- 5
32print(v1 == Vector.new(3, 0)) -- true (__eq)
33
34-- __call: make table callable
35local callable = setmetatable({}, {
36 __call = function(self, x)
37 return x * x
38 end
39})
40print(callable(5)) -- 25
READY · 40 lines
