Operator Overloading

Operator overloading lets a class define how operators like +, - and == behave. This allows for your custom types to feel more natural to use.

class Vector {
    X = 0
    Y = 0

    Vector(x = 0, y = 0) {
        this.X = x;
        this.Y = y;
    }

    operator +(other: Vector): Vector {
        local result = new Vector();
        result.X = this.X + other.X;
        result.Y = this.Y + other.Y;
        return result;
    }

    operator +(other: number): Vector {
        local result = new Vector();
        result.X = this.X + other;
        result.Y = this.Y + other;
        return result;
    }

    operator -(): Vector {
        local result = new Vector();
        result.X = -this.X;
        result.Y = -this.Y;
        return result;
    }

    operator ==(other: Vector): bool {
        return this.X == other.X && this.Y == other.Y;
    }

    operator <(other: Vector): bool {
        return this.X < other.X && this.Y < other.Y;
    }

    operator <=(other: Vector): bool {
        return this.X <= other.X && this.Y <= other.Y;
    }
}

With above define operators, we can now use them with our custom Vector class.

local a = new Vector(1, 2);
local b = new Vector(3, 4);

local c = a + b;
print(c.X); // 4
print(c.Y); // 6

local d = a + 10;
print(d.X); // 11
print(d.Y); // 12

local e = -a;
print(e.X); // -1
print(e.Y); // -2

print(a == new Vector(1, 2)); // true
print(a < new Vector(5, 5));  // true
print(a <= new Vector(1, 2)); // true

Comparison Operators

Comparison operators must return bool. The following comparison operators are supported:

  • ==
  • <
  • <=

These operators are derived automatically:

  • != (opposite of ==)
  • > (opposite of <)
  • >= (opposite of <=)
class Score {
    Value = 0

    operator ==(other: Score): bool {
        return this.Value == other.Value;
    }
}

Arithmetic Operators

Arithmetic operators can return any type. The following arithmetic operators are supported:

  • +
  • -
  • *
  • /
  • %
  • ^
  • unary -
class Label {
    Text = ""

    operator +(other: number): string {
        return this.Text + other;
    }
}

Multiple overloads

A class can define more than one overload of the same operator, as long as the parameter types do not overlap.

class Value {
    operator +(other: number): Value {
        return this;
    }

    operator +(other: string): Value {
        return this;
    }
}

Categories:

Updated: