Skip to content

Metamethods

Rohan Singh edited this page Feb 6, 2025 · 16 revisions

Metamethods are functions that are called when performing operations on objects. They are used to implement operator overloading but cannot override default behavior.

Metamethods are always called on the x value of the operation and will pass all relevant values to the handler (x, y, z, w in the table).

Proxy objects may also be of interest as they allow intercepting reads and writes to values of an object.

Usage

Metamethods can be set for an object by setting special indexes to the function you want it to call.

const endl = {};
const cout = {
    __lshift: fun (left, right) {
        if (right == endl)
            printLn();
        else
            print(right);
            
        return left;
    }
};

cout << "hello " << "world" << endl;

List of Metamethods

Name Operation Called when...
__call x(...y) attempting to call the object
__eq x == y checking if the object is equal to another value, != negates the result of this
__gt x > y
__gte x >= y
__lt x < y
__lte x <= y
__in y in x note: called on x
__add x + y
__sub x - y
__mul x * y
__div x / y
__mod x % y
__pow x ** y
__neg -x
__and x & y
__or x | y
__xor x ^ y
__lshift x << y
__rshift x >> y
__not ~x
__slice x[y:z:w] missing values for y, z and w will be undefined
__number n/a implicitly converting the object to a number (passes x)
__bool n/a implicitly converting the object to a bool (passes x)
__string n/a implicitly or explicitly converting the object to a string (passes x)
__serialize n/a the object is being serialized, does not need to return a string (passes x)
__hash n/a the object is being used as a key in another object