Skip to content

Metamethods

Rohan Singh edited this page Feb 1, 2015 · 16 revisions

Metamethods are functions that are called when performing operations on objects. They are used to implement operator overloading.

Metamethods are not allowed to override existing behavior and will only be called for the left-most value in the operation. The object containing the metamethod (x) will be the first function argument and additional arguments will follow (y, z).

Metamethods for binary operators are a bit different. They can be called for either the left or right value, meaning the object containing the metamethod could either be x or y. If you need to know which value contains the metamethod, the third parameter (isRight or z, your choice) will be set to false if it's x or true if it's y. The metamethods that do this are marked with an asterisk (*).

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, isRight) {
        if (right == endl)
            printLn();
        else
            print(right);
            
        return left;
    }
};

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

List of Metamethods

Name Operation Called when...
__get x.y, x[y] attempting to get a value that does not exist in the object
__set x.y = z, x[y] = z attempting to set a value that does not exist in the object
__call x(...y) attempting to call the object
__eq x == y checking if the object is equal to another value
__gt x > y checking if the object is greater than another value, other operations are combinations of __eq and __gt
__in x in y
__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
__number n/a implicitly converting the object to a number
__bool n/a implciitly converting the object to a bool
__string n/a implicitly or explicitly converting the object to a string
__serialize n/a the object is being serialized, does not need to return a string