AngelScript
Registering operator behaviours

In order for AngelScript to know how to work with the application registered types, it is necessary to register some behaviours, for example for memory management.

The memory management behaviours are described with the registeration of registering reference types and value types.

Other advanced behaviours are described with the advanced types.

Most behaviours are implemented as ordinary class methods, except with specific names that the compiler can understand.

Operator overloads

In AngelScript all operator overloads are implemented as class methods with predefined names, which is different from C++ where both class methods and global functions may be used. Especially the dual operators, i.e. those that take two operands, usually has one implemented as a class method, and a global function for the reverse order.

Two register C++ operator overloads you'll use the methods described in How to get the address of the application function or method.

Example on how to register operator overloads

class MyClass
{
...
// The operator 'MyClass - int' has been implemented as a method
MyClass operator-(int) const;
// The operator 'int - MyClass' has been implemented as a global function
static MyClass operator-(int, const MyClass &);
}
void RegisterMyClass(asIScriptEngine *engine)
{
// Registering the operator 'MyClass - int'
engine->RegisterObjectMethod("MyClass", "MyClass opSub(int) const", asMETHODPR(MyClass, operator-, (int) const, MyClass), asCALL_THISCALL);
// Registering the operator 'int - MyClass'
engine->RegisterObjectMethod("MyClass", "MyClass opSub_r(int) const", asFUNCTIONPR(operator-, (int, const MyClass &), MyClass), asCALL_CDECL_OBJLAST);
}

Value cast operators

The value cast operators are used to allow the scripts to convert an object type to another type by constructing a new value. This is different from a reference cast, that do not construct new values, but rather changes the way it is perceived.

By registering the behaviour either as asBEHAVE_VALUE_CAST or asBEHAVE_IMPLICIT_VALUE_CAST you let AngelScript know whether the behaviour may be used to implicitly cast the type or not.

// Convert a string to an int
int ConvStringToInt(const std::string &s)
{
return atoi(s.c_str());
}
// Register the behaviour
r = engine->RegisterObjectBehaviour("string", asBEHAVE_VALUE_CAST, "int f() const", asFUNCTION(ConvStringToInt), asCALL_CDECL_OBJLAST); assert( r >= 0 );

The return type for the cast behaviour can be any type except bool and void. The value cast is meant to create a new value, so if the function returns a reference or an object handle make sure it points to a new value and not the original one.

The object constructors and factories also serve as alternative explicit value cast operators, so if a constructor or factory is already available then there is no need to register the explicit value cast operator.