Operator overloads

It is possible to define what should be done when an operator is used with a script class. While not necessary in most scripts it can be useful to improve readability of the code.

This is called operator overloading, and is done by implementing specific class methods. The compiler will recognize and use these methods when it compiles expressions involving the overloaded operators and the script class.

Unary operators

opopfunc
- opNeg
~ opCom

When the expression op a is compiled, the compiler will rewrite it as a.opfunc and compile that instead.

Comparison operators

opopfunc
== opEquals
!= opEquals
< opCmp
<= opCmp
> opCmp
>= opCmp

The a == b expression will be rewritten as a.opEquals(b) and b.opEquals(a) and then the best match will be used. != is treated similarly, except that the result is negated. The opEquals method must be implemented to return a bool in order to be considered by the compiler.

The comparison operators are rewritten as a.opCmp(b) op 0 and 0 op b.opCmp(a) and then the best match is used. The opCmp method must be implemented to return a int in order to be considered by the compiler.

If an equality check is made and the opEquals method is not available the compiler looks for the opCmp method instead. So if the opCmp method is available it is really not necesary to implement the opEquals method, except for optimization reasons.

Assignment operators

opopfunc
= opAssign
+= opAddAssign
-= opSubAssign
*= opMulAssign
/= opDivAssign
%= opModAssign
&= opAndAssign
|= opOrAssign
^= opXorAssign
<<= opShlAssign
>>= opShrAssign
>>>= opUShrAssign

The assignment expressions a op b are rewritten as a.opfunc(b) and then the best matching method is used. An assignment operator can for example be implemented like this:

  obj@ opAssign(const obj &in other)
  {
    // Do the proper assignment
    ...

    // Return a handle to self, so that multiple assignments can be chained
    return this;
  }

All script classes have a default assignment operator that does a bitwise copy of the content of the class, so if that is all you want to do, then there is no need to implement this method.

Binary operators

opopfuncopfunc_r
+ opAdd opAdd_r
- opSub opSub_r
* opMul opMul_r
/ opDiv opDiv_r
% opMod opMod_r
& opAnd opAnd_r
| opOr opOr_r
^ opXor opXor_r
<< opShl opShl_r
>> opShr opShr_r
>>> opUShr opUShr_r

The expressions with binary operators a op b will be rewritten as a.opfunc(b) and b.opfunc_r(a) and then the best match will be used.


Generated on Sun Oct 18 16:43:42 2009 for AngelScript by  doxygen 1.5.9