Search code examples
c#reflectionclearscript

Overloading operators in ClearScript


I'm trying to utilize custom operators for arithmetic on custom classes in my application, which is interfaced to with ClearScript. Below is a snippet of my example custom class:

public class Vector3 {
    public float x { get; set; }
    public float y { get; set; }
    public float z { get; set; }

    public Vector3(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public static Vector3 operator +(Vector3 a, Vector3 b) {
        return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
    }
}

My ClearScript engine is initialized properly, and I can correctly initialize Vector3 objects through Javascript, and modify the properties accordingly.

However, if I initialize 2 Vector3 objects in the Javascript environment, and attempt to use the Javascript addition operator, it ends up evaluating the addition operator as string concatenation, not my custom operator.

Example:

var a = new Vector3(1, 1, 1);
var b = new Vector3(0, 2, -1);

var c = a + b;

print(typeof a); //returns "function" (which is correct)
print(typeof b); //returns "function" (which is also correct)

print(typeof c); //returns "string" (should return function)

The variable c only contains the string ([object HostObject][object HostObject]), instead of the Vector3 object.

How do I let the Javascript engine know to call my custom operator instead of using the default Javascript operators using ClearScript?


Solution

  • JavaScript's + operator returns the result of numeric addition or string concatenation. You can't overload it. Objects can override valueOf and/or toString to affect operand conversion, but there's no way to override the operation itself.

    If you can't call your custom operator directly from JavaScript, try adding a normal method that wraps it:

    public Vector3 Add(Vector3 that) { return this + that; }
    

    Then, in JavaScript:

    var c = a.Add(b);
    

    It isn't as elegant, but it should work.