Lesson 32 of 55
9 mins readPython Arithmetic Metamethods (__add, __sub, __mul)
In Plain English
Arithmetic metamethods (`__add`, `__sub`, `__mul`, `__div`, `__mod`, `__pow`, `__unm`, `__concat`) allow user-defined tables like vectors or complex numbers to use native math operators.
Deep Dive: How It Works
__add Metamethod: Intercepts the `+` operator when either operand is a table with `__add`.
Vector Addition: `v1 + v2` invokes `meta.__add(v1, v2)`.
__concat: Intercepts the `..` string concatenation operator.
Core Rules to Remember

Operator Overloading: Enables clean mathematical vector and matrix syntax.

__add, __sub, __mul: Map directly to `+`, `-`, and `*`.
Live Interactive Example
Hit Run Code to see it liveVector Math with __add Metamethod
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: a + b invoked the __add metamethod, returning a new vector table.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Overload __sub Operator
Create a metatable with `__sub = function(a, b) return { x = a.x - b.x } end`.
Set on `local p1 = { x = 10 }` and `local p2 = { x = 4 }`.
Print `"Diff: " .. (p1 - p2).x`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.