Operator Overloading

Jai supports operator overloading. Operators that can be overloaded include: +, -, *, /, ==, !=, <<, >>, &, |, [], %, ^, <<<, >>>. Operator overloading should be used conservatively, limited only to mathematical operations.

Given a Vector3 datatype, you can define an operator + for it. Defining operator + automatically defines operator += and vice versa.

Note: Even though you can overload +=, -=, *=, etc., you cannot overload operator =. Overloading operator = can cause a lot of confusion in which one may think one is just assigning a variable, but is accidentally calling operator =, causing a massive slowdown in the code.

Vector3 :: struct { x: float; y: float; z: float;} // Vector3 of {x,y,z}

operator + :: (a: Vector3, b: Vector3)->Vector3 {
  c: Vector3;
  c.x = a.x + b.x;
  c.y = a.y + b.y;
  c.z = a.z + b.z;
  return c;
}

a := Vector3.{1.0, 2.0, 3.0};
b := Vector3.{3.0, 4.0, 2.5};
c := a + b;
c += a;

symmetric keyword

Adding the keyword #symmetric to any two parameter function causes the order of two parameters to be irrelevant. We can define operator * on a Vector3 to mean scalar multiplication:

operator *:: (a: Vector3, b: float)->Vector3 #symmetric {
  b: Vector3;
  b.x = a.x * b;
  b.y = a.y * b;
  b.z = a.z * b;
  return b;
}

a := Vector3.{3.0, 4.0, 5.0};
c := a * 3;
c  = 3 * a;

As the example above shows, the #symmetric keyword allows someone to create a Vector3 with an operator * that can perform both a * 3 and 3 * a.

Operator Overloading Examples

Here is an example of using operator [].

Obj :: struct {
  array: [10] int;
}

operator [] :: (obj: Obj, i: int) -> int {
  return obj.array[i];
}

o : Obj;
print("o[0] = %\n", o[0]);

Here is an example of using operator *=.

operator *= :: (obj: *Obj, scalar: int) {
  for *a : obj.array
    <<a *= scalar;
}

o : Obj;
o *= 100;

Operators that you can NOT overload

operator = can not be overloaded. Although you can overload +=, -=, *=, etc., you cannot overload operator =. Overloading operator = can cause a lot of confusion in which one may think one is just assigning a variable, but is accidentally calling operator =, causing a massive slowdown in the code.

operator new can not be overloaded. New in Jai is a regular function call, not a keyword built into the language. You can change the context of the New function, and that is the way you can change the allocator.

1 Like