Chapter II · Idioms & deeper language / Lesson 12 of 27

Operator overloading

You'll learn: Implement __add, __eq, __tostring, and __call so a Vector feels like a native value.

Metamethods customise operators (__add, __sub, __mul, __div, __unm, __pow, __concat), equality (__eq), ordering (__lt, __le), length (__len), stringification (__tostring), and the call protocol (__call). Pair them with __index = self to make instance methods discoverable.

metatables-ops.lua
Output idle
Hit Run to execute.
Try it: Add a __sub metamethod and a :dot(other) method. Use them: print((a - b):dot(a + b)).