Lesson 33 of 55
8 mins readPython Relational Metamethods (__eq, __lt, __le)
In Plain English
Relational metamethods allow custom tables to be compared: `__eq` (for `==` and `~=`), `__lt` (for `<` and `>`), and `__le` (for `<=` and `>=`).
Deep Dive: How It Works
__eq: Invoked for `a == b` when both operands share the same `__eq` metamethod.
__lt: Invoked for `a < b`. Lua automatically translates `a > b` into `b < a`.
__le: Invoked for `a <= b`. Lua translates `a >= b` into `b <= a`.
Core Rules to Remember

__eq for Equality: Compares table contents instead of default reference identity.

Automatic Inversion: `a > b` automatically evaluates using `b < a` via `__lt`.
Live Interactive Example
Hit Run Code to see it liveComparing Box Volumes with __lt
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: __lt and __eq metamethods handled the relational comparisons.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Implement __eq Comparison
Define `local mt = { __eq = function(a, b) return a.id == b.id end }`.
Set on `local u1 = { id = 42 }` and `local u2 = { id = 42 }`.
Print `"Equal ID: " .. tostring(u1 == u2)`.
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.