samedi 25 février 2017

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)

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





Aucun commentaire:

Enregistrer un commentaire