code:
/**

\page doc_addon Add-ons

This page gives a brief description of the add-ons that you'll find in the /sdk/add_on/ folder.

 - \subpage doc_addon_application
 - \subpage doc_addon_script

\page doc_addon_application Application modules

 - \subpage doc_addon_build
 - \subpage doc_addon_ctxmgr
 - \subpage doc_addon_debugger
 - \subpage doc_addon_serializer
 - \subpage doc_addon_helpers
 - \subpage doc_addon_autowrap

\page doc_addon_script Script extensions

 - \subpage doc_addon_std_string
 - \subpage doc_addon_array
 - \subpage doc_addon_any
 - \subpage doc_addon_handle
 - \subpage doc_addon_weakref
 - \subpage doc_addon_dict
 - \subpage doc_addon_file
 - \subpage doc_addon_filesystem
 - \subpage doc_addon_math
 - \subpage doc_addon_grid
 - \subpage doc_addon_datetime
 - \subpage doc_addon_helpers_try

\todo add socket

\page doc_addon_datetime datetime object

Path: /sdk/add_on/datetime/

The CDateTime class provides a way for scripts to get the system date and time.

Register the type with the RegisterScriptDateTime(asIScriptEngine*) function.

\note This class requires C++11 or later to compile.

\section doc_addon_datetime_1 Public C++ interface

\code
class CDateTime
{
public:
  // Constructors
  CDateTime();
  CDateTime(const CDateTime &other);
  CDateTime(asUINT year, asUINT month, asUINT day, asUINT hour, asUINT minute, asUINT second);

  // Copy the stored value from another any object
  CDateTime &operator=(const CDateTime &other);

  // Accessors
  asUINT getYear() const;
  asUINT getMonth() const;
  asUINT getDay() const;
  asUINT getHour() const;
  asUINT getMinute() const;
  asUINT getSecond() const;
  asUINT getWeekDay() const;

  // Setters
  // Returns true if valid
  bool setDate(asUINT year, asUINT month, asUINT day);
  bool setTime(asUINT hour, asUINT minute, asUINT second);

  // Operators
  // Return difference in seconds
  asINT64          operator-(const CDateTime &other) const;
  CDateTime        operator+(asINT64 seconds) const;
  friend CDateTime operator+(asINT64 seconds, const CDateTime &other);
  CDateTime &      operator+=(asINT64 seconds);
  CDateTime        operator-(asINT64 seconds) const;
  friend CDateTime operator-(asINT64 seconds, const CDateTime &other);
  CDateTime &      operator-=(asINT64 seconds);
  bool             operator==(const CDateTime &other) const;
  bool             operator<(const CDateTime &other) const;
};
\endcode

\section doc_addon_datetime_2 Public script interface

\see \ref doc_script_stdlib_datetime "datetime in the script language"

\page doc_addon_serializer Serializer

Path: /sdk/add_on/serializer/

The CSerializer implements support for serializing the values of global variables in a
module, for example in order to reload a slightly modified version of the script without reinitializing
everything. It will resolve primitives and script classes automatically, including references and handles.

For application registered types, the application needs to implement callback objects to show how
these should be serialized. The exception is for pod types, as the serializer will simply keep a bitwise copy.
Registered reference types without factories will not be serialized, i.e. the object will be kept as-is.

The implementation currently has some limitations:

 - It can only serialize to memory, i.e. it is not possible to save the values to a file.
 - If the variables changed type when restoring, the serializer cannot restore the value.
 - The serializer will attempt to backup all objects, but in some cases an application may
   not want to backup the actual object, but only a reference to it, e.g. an internal application
   object referenced by the script. Currently there is no way of telling the serializer to do
   differently in this case.
 - If the module holds references to objects from another module it will probably fail in
   restoring the values.

\section doc_addon_serializer_1 Public C++ interface

\code
class CSerializer
{
public:
  CSerializer();
  ~CSerializer();

  // Clear the serializer to free references held internally
  void Clear();

  // Add implementation for serializing user types
  void AddUserType(CUserType *ref, const std::string &name);

  // Store all global variables in the module
  int Store(asIScriptModule *mod);

  // Restore all global variables after reloading script
  int Restore(asIScriptModule *mod);

  // Store extra objects that are not seen from the module's global variables
  void AddExtraObjectToStore(asIScriptObject *object);

  // Return new pointer to restored object
  void *GetPointerToRestoredObject(void *originalObject);
};
\endcode

\section doc_addon_serializer_2 Example usage

This first example shows how to serialize a script module that uses application registered types.

\code
struct CStringType;
struct CArrayType;

void RecompileModule(asIScriptEngine *engine, asIScriptModule *mod)
{
  string modName = mod->GetName();

  // Tell the serializer how the user types should be serialized
  // by adding the implementations of the CUserType interface
  CSerializer backup;
  backup.AddUserType(new CStringType(), "string");
  backup.AddUserType(new CArrayType(), "array");

  // Backup the values of the global variables
  backup.Store(mod);

  // Application can now recompile the module
  CompileModule(modName);

  // Restore the values of the global variables in the new module
  mod = engine->GetModule(modName.c_str(), asGM_ONLY_IF_EXISTS);
  backup.Restore(mod);
}

// This serializes the std::string type
struct CStringType : public CUserType
{
  void *AllocateUnitializedMemory(CSerializedValue* value)
  {
	// This must not be done for strings
	assert(false);
	return 0;
  }
  void Store(CSerializedValue *val, void *ptr)
  {
    val->SetUserData(new std::string(*(std::string*)ptr));
  }
  void Restore(CSerializedValue *val, void *ptr)
  {
    std::string *buffer = (std::string*)val->GetUserData();
    *(std::string*)ptr = *buffer;
  }
  void CleanupUserData(CSerializedValue *val)
  {
    std::string *buffer = (std::string*)val->GetUserData();
    delete buffer;
  }
};

// This serializes the CScriptArray type
struct CArrayType : public CUserType
{
  void* AllocateUnitializedMemory(CSerializedValue* value)
  {
	CScriptArray* arr = CScriptArray::Create(value->GetType());
	return arr;
  }
  void Store(CSerializedValue *val, void *ptr)
  {
    CScriptArray *arr = (CScriptArray*)ptr;

    for( unsigned int i = 0; i < arr->GetSize(); i++ )
      val->m_children.push_back(new CSerializedValue(val ,"", "", arr->At(i), arr->GetElementTypeId()));
  }
  void Restore(CSerializedValue *val, void *ptr)
  {
    CScriptArray *arr = (CScriptArray*)ptr;
    arr->Resize(asUINT(val->m_children.size()));

    for( size_t i = 0; i < val->m_children.size(); ++i )
      val->m_children[i]->Restore(arr->At(asUINT(i)), arr->GetElementTypeId());
  }
};
\endcode

The following example shows how to serialize additional objects, not stored in the module itself.

\code
// This object is stored outside of the module, so it has to be explicitly informed to the serializer
asIScriptObject *scriptObj = reinterpret_cast<asIScriptObject*>(engine->CreateScriptObject(mod->GetTypeInfoByName("CTest")));

void RecompileModule(asIScriptEngine *engine, asIScriptModule *mod)
{
  string modName = mod->GetName();

  // Tell the serializer about the additional object stored outside of the module
  CSerializer backup;
  backup.AddExtraObjectToStore(scriptObj);

  // Backup the values of the global variables and the additional object
  r = backup.Store(mod);
  if( r < 0 )
    TEST_FAILED;

  // Application can now recompile the module
  CompileModule(modName);

  // Restore the values of the global variables in the new module
  mod = engine->GetModule(modName.c_str(), asGM_ONLY_IF_EXISTS);
  backup.Restore(mod);

  // Restore the extra object by looking up the new instance using the address of the old instance as key
  asIScriptObject *obj2 = (asIScriptObject*)backup.GetPointerToRestoredObject(scriptObj);
  scriptObj->Release();
  scriptObj = obj2;
  scriptObj->AddRef();
}
\endcode

\page doc_addon_debugger Debugger

Path: /sdk/add_on/debugger/

The CDebugger implements common debugging functionality for scripts, e.g.
setting breakpoints, stepping through the code, examining values of variables, etc.

To use the debugger the line callback should be set in the context. This will allow the
debugger to take over whenever a breakpoint is reached, so the script can be debugged.

By default the debugger uses the standard in and standard out streams to interact with the
user, but this can be easily overloaded by deriving from the CDebugger class and implementing
the methods TakeCommands and Output. With this it is possible to implement a graphical
interface, or even remote debugging for an application.

The application developer may also be interested in registering to-string callbacks for registered types
with calls to RegisterToStringCallback. Optionally the ToString method in the
debugger can be overridden to implement custom to-string logic.

\see The sample \ref doc_samples_asrun for a complete example of how to use the debugger

\section doc_addon_debugger_1 Public C++ interface

\code
class CDebugger
{
public:
  CDebugger();
  virtual ~CDebugger();

  // Register callbacks to handle to-string conversions of application types
  // The expandMembersLevel is a counter for how many recursive levels the members should be expanded.
  // If the object that is being converted to a string has members of its own the callback should call
  // the debugger's ToString passing in expandMembersLevel - 1.
  typedef std::string (*ToStringCallback)(void *obj, int expandMembersLevel, CDebugger *dbg);
  virtual void RegisterToStringCallback(const asITypeInfo *type, ToStringCallback callback);

  // User interaction
  virtual void TakeCommands(asIScriptContext *ctx);
  virtual void Output(const std::string &str);

  // Line callback invoked by context
  virtual void LineCallback(asIScriptContext *ctx);

  // Commands
  virtual void PrintHelp();
  virtual void AddFileBreakPoint(const std::string &file, int lineNbr);
  virtual void AddFuncBreakPoint(const std::string &func);
  virtual void ListBreakPoints();
  virtual void ListLocalVariables(asIScriptContext *ctx);
  virtual void ListGlobalVariables(asIScriptContext *ctx);
  virtual void ListMemberProperties(asIScriptContext *ctx);
  virtual void ListStatistics(asIScriptContext *ctx);
  virtual void PrintCallstack(asIScriptContext *ctx);
  virtual void PrintValue(const std::string &expr, asIScriptContext *ctx);

  // Helpers
  virtual bool InterpretCommand(const std::string &cmd, asIScriptContext *ctx);
  virtual bool CheckBreakPoint(asIScriptContext *ctx);
  virtual std::string ToString(void *value, asUINT typeId, int expandMembersLevel, asIScriptEngine *engine);

  // Optionally set the engine pointer in the debugger so it can be retrieved
  // by callbacks that need it. This will hold a reference to the engine.
  virtual void SetEngine(asIScriptEngine *engine);
  virtual asIScriptEngine *GetEngine();
};
\endcode

\section doc_addon_debugger_2 Example usage

\code
CDebugger dbg;
int ExecuteWithDebug(asIScriptContext *ctx)
{
  // Tell the context to invoke the debugger's line callback
  ctx->SetLineCallback(asMETHOD(CDebugger, LineCallback), &dbg, asCALL_THISCALL);

  // Allow the user to initialize the debugging before moving on
  dbg.TakeCommands(ctx);

  // Execute the script normally. If a breakpoint is reached the
  // debugger will take over the control loop.
  return ctx->Execute();
}
\endcode

\page doc_addon_ctxmgr Context manager

Path: /sdk/add_on/contextmgr/

The CContextMgr is a class designed to aid the management of multiple simultaneous
scripts executing in parallel. It supports both \ref doc_adv_concurrent "concurrent script threads"
and \ref doc_adv_coroutine "co-routines".

If the application doesn't need multiple contexts, i.e. all scripts that are executed
always complete before the next script is executed, then this class is not necessary.

The context manager uses \ref asIScriptEngine::RequestContext to take advantage of any context
callbacks registered with the engine, e.g. for debugging or pooling.

Multiple context managers can be used, for example when you have a group of scripts controlling
in-game objects, and another group of scripts controlling GUI elements, then each of these groups
may be managed by different context managers.

Observe that the context manager class hasn't been designed for multi-threading, so you need to
be careful if your application needs to execute scripts from multiple threads.

\see The samples \ref doc_samples_concurrent and \ref doc_samples_corout for uses

\section doc_addon_ctxmgr_1 Public C++ interface

\code
class CContextMgr
{
public:
  CContextMgr();
  ~CContextMgr();

  // Set the function that the manager will use to obtain the time in milliseconds.
  void SetGetTimeCallback(TIMEFUNC_t func);

  // Registers the following:
  //
  //  void sleep(uint milliseconds)
  //
  // The application must set the get time callback for this to work
  void RegisterThreadSupport(asIScriptEngine *engine);

  // Registers the following:
  //
  //  funcdef void coroutine(dictionary@)
  //  void createCoRoutine(coroutine @func, dictionary @args)
  //  void yield()
  void RegisterCoRoutineSupport(asIScriptEngine *engine);

  // Create a new context, prepare it with the function, then return
  // it so that the application can pass the argument values. The context
  // will be released by the manager after the execution has completed.
  // Set keepCtxAfterExecution to true if the application needs to retrieve
  // information from the context after it the script has finished.
  asIScriptContext *AddContext(asIScriptEngine *engine, asIScriptContext *func, bool keepCtxAfterExecution = false);

  // If the context was kept after the execution, this method must be
  // called when the application is done with the context so it can be
  // returned to the pool for reuse.
  void DoneWithContext(asIScriptContext *ctx);

  // Create a new context, prepare it with the function, then return
  // it so that the application can pass the argument values. The context
  // will be added as a co-routine in the same thread as the currCtx.
  asIScriptContext *AddContextForCoRoutine(asIScriptContext *currCtx, asIScriptContext *func);

  // Execute each script that is not currently sleeping. The function returns after
  // each script has been executed once. The application should call this function
  // for each iteration of the message pump, or game loop, or whatever.
  // Returns the number of scripts still in execution.
  int ExecuteScripts();

  // Put a script to sleep for a while
  void SetSleeping(asIScriptContext *ctx, asUINT milliSeconds);

  // Switch the execution to the next co-routine in the group.
  // Returns true if the switch was successful.
  void NextCoRoutine();

  // Abort all scripts
  void AbortAll();
};
\endcode

\section doc_addon_ctxmgr_2 Public script interface

\see \ref doc_script_stdlib_coroutine

\page doc_addon_array array template object

Path: /sdk/add_on/scriptarray/

The array type is a \ref doc_adv_template "template object" that allow the scripts to declare arrays of any type.
Since it is a generic class it is not the most performatic due to the need to determine characteristics at
runtime. For that reason it is recommended that the application registers a \ref doc_adv_template_2 "template specialization" for the
array types that are most commonly used.

The type is registered with RegisterScriptArray(asIScriptEngine *engine, bool defaultArrayType). The second
parameter should be set to true if you wish to allow the syntax form type[] to declare arrays.

Compile the add-on with the pre-processor define AS_USE_STLNAMES=1 to register the methods with the same names as used by C++ STL where
the methods have the same significance. Not all methods from STL is implemented in the add-on, but many of the most frequent once are
so a port from script to C++ and vice versa might be easier if STL names are used.

Compile the add-on with the pre-processor define AS_USE_ACCESSORS=1 to register length as a virtual property instead of the method length().

Compile the add-on with the pre-processor define AS_NO_IMPL_OPS_WITH_STRING_AND_PRIMITIVE=1 to disable the implicit operations with
primitives that automatically formats the primitive values to strings.

\section doc_addon_array_1 Public C++ interface

\code
class CScriptArray
{
public:
  // Set the memory functions that should be used by all CScriptArrays
  static void SetMemoryFunctions(asALLOCFUNC_t allocFunc, asFREEFUNC_t freeFunc);

  // Factory functions
  static CScriptArray *Create(asITypeInfo *arrayType);
  static CScriptArray *Create(asITypeInfo *arrayType, asUINT length);
  static CScriptArray *Create(asITypeInfo *arrayType, asUINT length, void *defaultValue);
  static CScriptArray *Create(asITypeInfo *arrayType, void *listBuffer);

  // Memory management
  void AddRef() const;
  void Release() const;

  // Type information
  asITypeInfo   *GetArrayObjectType() const;
  int            GetArrayTypeId() const;
  int            GetElementTypeId() const;

  // Get the current size
  asUINT GetSize() const;

  // Returns true if the array is empty
  bool IsEmpty() const;

  // Pre-allocates memory for elements
  void Reserve(asUINT numElements);

  // Resize the array
  void Resize(asUINT numElements);

  // Get a pointer to an element. Returns 0 if out of bounds
  void       *At(asUINT index);
  const void *At(asUINT index) const;

  // Set value of an element.
  // The value arg should be a pointer to the value that will be copied to the element.
  // Remember, if the array holds handles the value parameter should be the
  // address of the handle. The refCount of the object will also be incremented
  void  SetValue(asUINT index, void *value);

  // Copy the contents of one array to another (only if the types are the same)
  CScriptArray &operator=(const CScriptArray&);

  // Compare two arrays
  bool operator==(const CScriptArray &) const;

  // Array manipulation
  void InsertAt(asUINT index, void *value);
  void RemoveAt(asUINT index);
  void InsertLast(void *value);
  void RemoveLast();
  void SortAsc();
  void SortAsc(asUINT startAt, asUINT count);
  void SortDesc();
  void SortDesc(asUINT startAt, asUINT count);
  void Sort(asUINT startAt, asUINT count, bool asc);
  void Sort(asIScriptFunction *less, asUINT startAt, asUINT count);
  void Reverse();
  int  Find(void *value) const;
  int  Find(asUINT startAt, void *value) const;
  int  FindByRef(void *ref) const;
  int  FindByRef(asUINT startAt, void *ref) const;

  // Returns the address of the inner buffer for direct manipulation
  void *GetBuffer();
};
\endcode

\section doc_addon_array_2 Public script interface

\see \ref doc_datatypes_arrays "Arrays in the script language"

\section doc_addon_array_4 C++ example

This function shows how a script array can be instantiated
from the application and then passed to the script.

\code
// Registered with AngelScript as 'array<string> @CreateArrayOfString()'
CScriptArray *CreateArrayOfStrings()
{
  // If called from the script, there will always be an active
  // context, which can be used to obtain a pointer to the engine.
  asIScriptContext *ctx = asGetActiveContext();
  if( ctx )
  {
    asIScriptEngine* engine = ctx->GetEngine();

    // The script array needs to know its type to properly handle the elements.
    // Note that the object type should be cached to avoid performance issues
    // if the function is called frequently.
    asITypeInfo* t = engine->GetTypeInfoByDecl("array<string>");

    // Create an array with the initial size of 3 elements
    CScriptArray* arr = CScriptArray::Create(t, 3);
    for( asUINT i = 0; i < arr->GetSize(); i++ )
    {
      // Set the value of each element
      string val("test");
      arr->SetValue(i, &val);
    }

    // The ref count for the returned handle was already set in the array's constructor
    return arr;
  }
  return 0;
}
\endcode

\page doc_addon_grid grid template object

Path: /sdk/add_on/scriptgrid/

The grid type is a \ref doc_adv_template "template object" that allow the scripts to declare 2D grids of any type.
In many ways it is similar to the \ref doc_addon_array, but it is specialized for use with areas.

The type is registered with RegisterScriptGrid(asIScriptEngine *engine).

\section doc_addon_grid_1 Public C++ interface

\code
class CScriptGrid
{
public:
  // Set the memory functions that should be used by all CScriptGrids
  static void SetMemoryFunctions(asALLOCFUNC_t allocFunc, asFREEFUNC_t freeFunc);

  // Factory functions
  static CScriptGrid *Create(asITypeInfo *gridType);
  static CScriptGrid *Create(asITypeInfo *gridType, asUINT width, asUINT height);
  static CScriptGrid *Create(asITypeInfo *gridType, asUINT width, asUINT height, void *defaultValue);
  static CScriptGrid *Create(asITypeInfo *gridType, void *listBuffer);

  // Memory management
  void AddRef() const;
  void Release() const;

  // Type information
  asITypeInfo   *GetGridObjectType() const;
  int            GetGridTypeId() const;
  int            GetElementTypeId() const;

  // Size
  asUINT GetWidth() const;
  asUINT GetHeight() const;
  void   Resize(asUINT width, asUINT height);

  // Get a pointer to an element. Returns 0 if out of bounds
  void       *At(asUINT x, asUINT y);
  const void *At(asUINT x, asUINT y) const;

  // Set value of an element.
  // The value arg should be a pointer to the value that will be copied to the element.
  // Remember, if the grid holds handles the value parameter should be the
  // address of the handle. The refCount of the object will also be incremented
  void  SetValue(asUINT x, asUINT y, void *value);
};
\endcode

\section doc_addon_grid_2 Public script interface

  class grid<T>
  {
    grid();
    grid(uint width, uint height);
    grid(uint width, uint height, const T &in fillValue);

    uint width() const;
    uint height() const;
    void resize(uint w, uint h);

    T &opIndex(uint x, uint y);
    const T &opIndex(uint x, uint y) const;
  }

grid()

grid(uint width, uint height)

grid(uint width, height, const T &in fillValue)

The constructors initializes the grid object. The default constructor will create an zero sized grid.

uint width() const

uint height() const

Returns the width and height of the grid.

void resize(uint w, uint h)

Resizes the grid to the new dimension. The elements that still fit in the grid will keep their values.

T &opIndex(uint x, uint y)

const T &opIndex(uint x, uint y) const

The index operator returns a reference to one of the elements. If the index is out of bounds a script
exception will be raised.

\section doc_addon_grid_3 Example usage in script

  // Initialize a 5x5 map
  grid<int> map = {{1,0,1,1,1},
                   {0,0,1,0,0},
                   {0,1,1,0,1},
                   {0,1,1,0,1},
                   {0,0,0,0,1}};

  // A function to verify if the next area is walkable
  bool canWalk(uint x, uint y)
  {
    // If the map in the destination is
    // clear, it is possible to wark there
    return map[x,y] == 0;
  }

\page doc_addon_any any object

Path: /sdk/add_on/scriptany/

The any type is a generic container that can hold any value. It is a reference type.

The type is registered with RegisterScriptAny(asIScriptEngine*).

\section doc_addon_any_1 Public C++ interface

\code
class CScriptAny
{
public:
  // Constructors
  CScriptAny(asIScriptEngine *engine);
  CScriptAny(void *ref, int refTypeId, asIScriptEngine *engine);

  // Memory management
  int AddRef() const;
  int Release() const;

  // Copy the stored value from another any object
  CScriptAny &operator=(const CScriptAny&);
  int CopyFrom(const CScriptAny *other);

  // Store the value, either as variable type, integer number, or real number
  void Store(void *ref, int refTypeId);
  void Store(asINT64 &value);
  void Store(double &value);

  // Retrieve the stored value, either as variable type, integer number, or real number
  bool Retrieve(void *ref, int refTypeId) const;
  bool Retrieve(asINT64 &value) const;
  bool Retrieve(double &value) const;

  // Get the type id of the stored value
  int GetTypeId() const;
};
\endcode

\section doc_addon_any_2 Public script interface

  class any
  {
    any();
    any(? &in value);
    any(int64 &in value);
    any(double &in value);

    any &opAssign(const any &in other);

    void store(? &in value);
    void store(int64 &in value);
    void store(double &in value);

    bool retrieve(? &out value) const;
    bool retrieve(int64 &out value) const;
    bool retrieve(double &out value) const;
  }

any()

any(? &in value)

any(int64 &in value)

any(double &in value)

The default constructor creates an empty object, and the second initializes the object with the provided value.

The int64 and double overloads make sure that all numbers are converted to 64bit before being stored in the object.

any &opAssign(const any &in other)

The assignment operator will copy the contained value from the other object.

void store(? &in value)

void store(int64 &in value)

void store(double &in value)

These methods sets the value in the object.

The int64 and double overloads make sure that all numbers are converted to 64bit before being stored in the object.

bool retrieve(? &out value) const

bool retrieve(int64 &out value) const

bool retrieve(double &out value) const

These methods retrieve the value stored in the object. The methods will return true if the stored value is
compatible with the requested type.

\section doc_addon_any_3 Example usage

In the scripts it can be used as follows:

  int value;
  obj object;
  obj \@handle;
  any a,b,c;
  a.store(value);      // store the value
  b.store(\@handle);    // store an object handle
  c.store(object);     // store a copy of the object

  a.retrieve(value);   // retrieve the value
  b.retrieve(\@handle); // retrieve the object handle
  c.retrieve(object);  // retrieve a copy of the object

In C++ the type can be used as follows:

\code
CScriptAny *myAny;
int typeId = engine->GetTypeIdByDecl("string@");
CScriptString *str = new CScriptString("hello world");
myAny->Store((void*)&str, typeId);
myAny->Retrieve((void*)&str, typeId);
\endcode

\page doc_addon_handle ref object

Path: /sdk/add_on/scripthandle/

The ref type is a generic container that can hold any handle.
It is a value type, but behaves very much like an object handle.

The type is registered with RegisterScriptHandle(asIScriptEngine*).

\see \ref doc_adv_generic_handle

\section doc_addon_handle_1 Public C++ interface

\code
class CScriptHandle
{
public:
  // Constructors
  CScriptHandle();
  CScriptHandle(const CScriptHandle &other);
  CScriptHandle(void *ref, int typeId);
  ~CScriptHandle();

  // Copy the stored reference from another handle object
  CScriptHandle &operator=(const CScriptHandle &other);

  // Set the reference
  void Set(void *ref, asITypeInfo *type);

  // Compare equalness
  bool operator==(const CScriptHandle &o) const;
  bool operator!=(const CScriptHandle &o) const;
  bool opEquals(void *ref, int typeId) const;

  // Dynamic cast to desired handle type
  void Cast(void **outRef, int typeId);

  // Returns the type of the reference held
  asITypeInfo   *GetType() const;
  int            GetTypeId() const;

  // Returns the reference
  void *GetRef();
};
\endcode

\section doc_addon_handle_3 Public script interface

\see \ref doc_datatypes_ref "ref in the script language"

\section doc_addon_handle_4 Example usage from C++

Even though the CScriptHandle is a value type, when registering properties
of its type they should be registered as handles. The same goes for function
arguments and return types.

\code
CScriptHandle g_handle;

void Function(CScriptHandle handle)
{
  ... use the methods of CScriptHandle to determine the true object held in it
}

void Register(asIScriptEngine *engine)
{
  int r;
  r = engine->RegisterGlobalProperty("ref @g_handle", &g_handle); assert( r >= 0 );
  r = engine->RegisterGlobalFunction("void Function(ref @)", asFUNCTION(Function), asCALL_CDECL); assert( r >= 0 );
}
\endcode

To set an object pointer in the handle from the application, you'll use the
Set() method passing a pointer to the object and the type of the object.

To retrieve an object pointer from the application you'll use the Cast() method
passing in a pointer to the pointer and the wanted type id. If the type id given
doesn't match the stored handle the returned pointer will be null.

To retrieve an object of an unknown type use the GetType() or GetTypeId() to
determine the type stored in the handle, then use the Cast() method.

\section doc_addon_handle_5 Example on how to return a newly registered function from C++

The following is a bit more practical example of using the CScriptHandle to return a recently registered function. The
function could for example have been loaded from a shared library, based on informed function and name from the script.

\code
// This C++ function would be called from script, register a new C++ function and then return it to the script as a function pointer
// Register with engine->RegisterGlobalFunction("ref @getDynamicFunction()", asFUNCTION(getDynamicFunction), asCALL_CDECL);
CScriptHandle getDynamicFunction()
{
  // Get the active context and engine to register the function with
  asIScriptContext* ctx = asGetActiveContext();
  asIScriptEngine *engine = ctx->GetEngine();

  // Register the function. The actual function could be dynamically loaded from a shared library
  int funcId = engine->RegisterGlobalFunction("void dynamicFunction()", asFUNCTION(dynamicFunction), asCALL_CDECL);

  // Create the CScriptHandle and put the function pointer in it for return to script
  asIScriptFunction* func = engine->GetFunctionById(funcId);
  CScriptHandle ref;
  ref.Set(func, engine->GetTypeInfoById(func->GetTypeId()));

  return ref;
}
\endcode

In the script the this would be used in the following way:

  funcdef void func();
  void main()
  {
    // Get the function pointer as a generic ref
    ref \@r = getDynamicFunction();

    // Cast the ref to the expected function pointer
    func \@f = cast<func>(r);

    // Call the function
    f();
  }

\page doc_addon_weakref weakref object

Path: /sdk/add_on/weakref/

The weakref type is a template type for holding weak references to
objects, i.e. the references that will not keep the referred object alive.

The type is registered with RegisterScriptWeakRef(asIScriptEngine*).

\see \ref doc_adv_weakref

\section doc_addon_weakref_1 Public C++ interface

\code
class CScriptWeakRef
{
public:
  // Constructors
  CScriptWeakRef(asITypeInfo *type);
  CScriptWeakRef(const CScriptWeakRef &other);
  CScriptWeakRef(void *ref, asITypeInfo *type);

  ~CScriptWeakRef();

  // Copy the stored value from another weakref object
  CScriptWeakRef &operator=(const CScriptWeakRef &other);

  // Compare equalness
  bool operator==(const CScriptWeakRef &o) const;
  bool operator!=(const CScriptWeakRef &o) const;

  // Sets a new reference
  CScriptWeakRef &Set(void *newRef);

  // Returns the object if it is still alive
  // This will increment the refCount of the returned object
  void *Get() const;

  // Returns true if the contained reference is the same
  bool Equals(void *ref) const;

  // Returns the type of the reference held
  asITypeInfo *GetRefType() const;
};
\endcode

\section doc_addon_weakref_2 Public script interface

\see \ref doc_datatypes_weakref "weakref in the script language"

\page doc_addon_std_string string object

Path: /sdk/add_on/scriptstdstring/

This add-on registers the std::string type as-is with AngelScript. This gives
perfect compatibility with C++ functions that use std::string in parameters or
as return type.

A potential drawback is that the std::string type is a value type, thus may
increase the number of copies taken when string values are being passed around
in the script code. However, this is most likely only a problem for scripts
that perform a lot of string operations.

Register the type with RegisterStdString(asIScriptEngine*). Register the optional
split method and global join function with RegisterStdStringUtils(asIScriptEngine*).
The optional functions require that the \ref doc_addon_array has been registered first.

Compile the add-on with the pre-processor define AS_USE_STLNAMES=1 to register the methods with the same names as used by C++ STL where
the methods have the same significance. Not all methods from STL is implemented in the add-on, but many of the most frequent ones are
so a port from script to C++ and vice versa might be easier if STL names are used.

Compile the add-on with the pre-processor define AS_USE_ACCESSORS=1 to register length as a virtual property instead of the method length().

\section doc_addon_std_string_1 Public C++ interface

Refer to the std::string implementation for your compiler.

\section doc_addon_std_string_2 Public script interface

\see \ref doc_script_stdlib_string "Strings in the script language"

\page doc_addon_dict dictionary object

Path: /sdk/add_on/scriptdictionary/

The dictionary object maps string values to values or objects of other types.

Register with RegisterScriptDictionary(asIScriptEngine*).

Compile the add-on with the pre-processor define AS_USE_STLNAMES=1 to register the methods with the same names as used by C++ STL where
the methods have the same significance. Not all methods from STL is implemented in the add-on, but many of the most frequent once are
so a port from script to C++ and vice versa might be easier if STL names are used.

\section doc_addon_dict_1 Public C++ interface

\code
typedef std::string dictKey;

class CScriptDictionary
{
public:
  // Factory functions
  static CScriptDictionary *Create(asIScriptEngine *engine);

  // Reference counting
  void AddRef() const;
  void Release() const;

  // Perform a shallow copy of the other dictionary
  CScriptDictionary &operator=(const CScriptDictionary &other);

  // Sets a key/value pair
  void Set(const dictKey &key, void *value, int typeId);
  void Set(const dictKey &key, asINT64 &value);
  void Set(const dictKey &key, double &value);

  // Gets the stored value. Returns false if the value isn't compatible with informed type
  bool Get(const dictKey &key, void *value, int typeId) const;
  bool Get(const dictKey &key, asINT64 &value) const;
  bool Get(const dictKey &key, double &value) const;

  // Index accessors. If the dictionary is not const it inserts the value if it doesn't already exist
  // If the dictionary is const then a script exception is set if it doesn't exist and a null pointer is returned
  CScriptDictValue *operator[](const dictKey &key);
  const CScriptDictValue *operator[](const dictKey &key) const;

  // Returns the type id of the stored value, or negative if it doesn't exist
  int  GetTypeId(const dictKey &key) const;

  // Returns true if the key is set
  bool Exists(const dictKey &key) const;

  // Returns true if the dictionary is empty
  bool IsEmpty() const;

  // Returns the number of keys in the dictionary
  asUINT GetSize() const;

  // Deletes the key
  bool Delete(const dictKey &key);

  // Deletes all keys
  void DeleteAll();

  // Get an array of all keys
  CScriptArray *GetKeys() const;

  // STL style iterator
  class CIterator
  {
  public:
    void operator++();    // Pre-increment
    void operator++(int); // Post-increment

    bool operator==(const CIterator &other) const;
    bool operator!=(const CIterator &other) const;

    // Accessors
    const dictKey &GetKey() const;
    int            GetTypeId() const;
    bool           GetValue(asINT64 &value) const;
    bool           GetValue(double &value) const;
    bool           GetValue(void *value, int typeId) const;
    const void *   GetAddressOfValue() const;
  };

  CIterator begin() const;
  CIterator end() const;
  CIterator find(const dictKey &key) const;
};
\endcode

\section doc_addon_dict_2 Public script interface

\see \ref doc_datatypes_dictionary "Dictionaries in the script language"

\section doc_addon_dict_3 Example usage from C++

Here's a skeleton for iterating over the entries in the dictionary. For brevity the code doesn't show how to interpret the values,
for more information on that see \ref asETypeIdFlags and \ref asIScriptEngine::GetTypeInfoById.

\code
void iterateDictionary(CScriptDictionary *dict)
{
	// Iterate over each entry
	for (auto it : *dict)
	{
		// Determine the name of the key
		std::string keyName = it.GetKey();
		cout << "\"" << keyName << "\"" << " = ";

		// Get the type and address of the value
		int typeId = it.GetTypeId();
		const void *addressOfValue = it.GetAddressOfValue();

		// Cast the value to the correct C++ type according to the typeId and then print it
		...
	}
}
\endcode

\page doc_addon_file file object

Path: /sdk/add_on/scriptfile/

This object provides support for reading and writing files.

Register with RegisterScriptFile(asIScriptEngine*).

If you do not want to provide write access for scripts then you can compile
the add on with the define AS_WRITE_OPS 0, which will disable support for writing.
This define can be made in the project settings or directly in the header.

\section doc_addon_file_1 Public C++ interface

\code
class CScriptFile
{
public:
  // Constructor
  CScriptFile();

  // Memory management
  void AddRef() const;
  void Release() const;

  // Opening and closing file handles
  // mode = "r" -> open the file for reading
  // mode = "w" -> open the file for writing (overwrites existing files)
  // mode = "a" -> open the file for appending
  int Open(const std::string &filename, const std::string &mode);
  int Close();

  // Returns the size of the file
  int GetSize() const;

  // Returns true if the end of the file has been reached
  bool IsEOF() const;

  // Reads a specified number of bytes into the string
  std::string ReadString(unsigned int length);

  // Reads to the next new-line character
  std::string ReadLine();

  // Reads a signed integer
  asINT64     ReadInt(asUINT bytes);

  // Reads an unsigned integer
  asQWORD     ReadUInt(asUINT bytes);

  // Reads a float
  float       ReadFloat();

  // Reads a double
  double      ReadDouble();

  // Writes a string to the file
  int WriteString(const std::string &str);

  int WriteInt(asINT64 v, asUINT bytes);
  int WriteUInt(asQWORD v, asUINT bytes);
  int WriteFloat(float v);
  int WriteDouble(double v);

  // File cursor manipulation
  int GetPos() const;
  int SetPos(int pos);
  int MovePos(int delta);

  // Determines the byte order of the binary values (default: false)
  // Big-endian = most significant byte first
  bool mostSignificantByteFirst;
};
\endcode

\section doc_addon_file_2 Public script interface

\see \ref doc_script_stdlib_file

\page doc_addon_filesystem filesystem object

Path: /sdk/add_on/scriptfile/

This object provides support for inspecting directories on the filesystem.

Register with RegisterScriptFileSystem(asIScriptEngine*).

\section doc_addon_filesystem_1 Public C++ interface

\code
class CScriptFileSystem
{
public:
  CScriptFileSystem();

  void AddRef() const;
  void Release() const;

  // Sets the current path that should be used in other calls when using relative paths
  // It can use relative paths too, so moving up a directory is used by passing in ".."
  bool ChangeCurrentPath(const std::string &path);
  std::string GetCurrentPath() const;

  // Returns true if the path is a directory. Input can be either a full path or a relative path.
  // This method does not return the dirs '.' and '..'
  bool IsDir(const std::string &path) const;

  // Returns true if the path is a link. Input can be either a full path or a relative path
  bool IsLink(const std::string &path) const;

  // Returns the size of file. Input can be either a full path or a relative path
  asINT64 GetSize(const std::string &path) const;

  // Returns a list of the files in the current path
  CScriptArray *GetFiles() const;

  // Returns a list of the directories in the current path
  CScriptArray *GetDirs() const;

  // Creates a new directory. Returns 0 on success
  int MakeDir(const std::string &path);

  // Removes a directory. Will only remove the directory if it is empty. Returns 0 on success
  int RemoveDir(const std::string &path);

  // Deletes a file. Returns 0 on success
  int DeleteFile(const std::string &path);

  // Copies a file. Returns 0 on success
  int CopyFile(const std::string &source, const std::string &target);

  // Moves or renames a file or directory. Returns 0 on success
  int Move(const std::string &source, const std::string &target);

  // Gets the date and time of the file/dir creation
  CDateTime GetCreateDateTime(const std::string &path) const;

  // Gets the date and time of the file/dir modification
  CDateTime GetModifyDateTime(const std::string &path) const;
};
\endcode

\section doc_addon_filesystem_2 Public script interface

\see \ref doc_script_stdlib_filesystem

\page doc_addon_math math functions

Path: /sdk/add_on/scriptmath/

This add-on registers the math functions from the standard C runtime library with the script
engine. Use RegisterScriptMath(asIScriptEngine*) to perform the registration.

By defining the preprocessor word AS_USE_FLOAT=0, the functions will be registered to take
and return doubles instead of floats.

The function RegisterScriptMathComplex(asIScriptEngine*) registers a type that
represents a complex number, i.e. a number with real and imaginary parts.

\section doc_addon_math_1 Public script interface

  // Trigonometric functions
  float cos(float rad);
  float sin(float rad);
  float tan(float rad);

  // Inverse trigonometric functions
  float acos(float val);
  float asin(float val);
  float atan(float val);
  float atan2(float y, float x);

  // Hyperbolic functions
  float cosh(float rad);
  float sinh(float rad);
  float tanh(float rad);

  // Logarithmic functions
  float log(float val);
  float log10(float val);

  // Power to
  float pow(float val, float exp);

  // Square root
  float sqrt(float val);

  // Absolute value
  float abs(float val);

  // Ceil and floor functions
  float ceil(float val);
  float floor(float val);

  // Returns the fraction
  float fraction(float val);

  // Approximate float comparison, to deal with numeric imprecision
  bool closeTo(float a, float b, float epsilon = 0.00001f);
  bool closeTo(double a, double b, double epsilon = 0.0000000001);

  // Conversion between floating point and IEEE 754 representations
  float  fpFromIEEE(uint raw);
  double fpFromIEEE(uint64 raw);
  uint   fpToIEEE(float fp);
  uint64 fpToIEEE(double fp);

\subsection doc_addon_math_funcs Functions

cos, sin, tan

Calculates the trigonometric functions cosine, sine, and tangent. The input angle should be given in radian.

acos, asin, atan

Calculates the inverse of the trigonometric functions cosine, sine, and tangent. The returned angle is given in radian.

atan2

Calculates the inverse of the trigonometric function tangent. The input is the y and x proportions. The returned angle is given in radian.

cosh, sinh, tanh

Calculates the hyperbolic of the cosine, sine, and tangent. The input angle should be given in radian.

log, log10

Calculates the logarithm of the input value. log is the natural logarithm and log10 is the base-10 logarithm.

pow

Calculates the based raised to the power of exponent.

sqrt

Calculates the square root of the value.

abs

Returns the absolute value.

ceil, floor

ceil returns the closest integer number that is higher or equal to the input. Floor returns the closest integer number that is lower or equal to the input.

fraction

Returns the fraction of the number, i.e. what remains after taking away the integral number.

closeTo

Due to numerical errors with the binary representation of real numbers it is often difficult to do direct comparisons of two float values. The closeTo function will return true of the two values are almost equal, allowing for a small difference up to the size of the epsilon value.

fpFromIEEE, fpToIEEE

Translates the float to and from IEEE 754 representation. This can be used if one wishes to directly inspect or manipulate the floating point value in the binary representation.

\subsection doc_addon_math_complex The complex type

  // This type represents a complex number with real and imaginary parts
  class complex
  {
    // Constructors
    complex();
    complex(const complex &in);
    complex(float r);
    complex(float r, float i);

    // Equality operator
    bool opEquals(const complex &in) const;

    // Compound assignment operators
    complex &opAddAssign(const complex &in);
    complex &opSubAssign(const complex &in);
    complex &opMulAssign(const complex &in);
    complex &opDivAssign(const complex &in);

    // Math operators
    complex opAdd(const complex &in) const;
    complex opSub(const complex &in) const;
    complex opMul(const complex &in) const;
    complex opDiv(const complex &in) const;

    // Returns the absolute value (magnitude)
    float abs() const;

    // Swizzle operators
    complex get_ri() const;
    void set_ri(const complex &in);
    complex get_ir() const;
    void set_ir(const complex &in);

    // The real and imaginary parts
    float r;
    float i;
  }

complex

The constructors allow for implicit construction, making a copy, implicit conversion from float, and explicit initialization from two float values.

=, !=

Compares two complex values.

=, +=, -=, *=, /=

Assign and compound assignment of complex values.

+, -, *, /

Math operators on complex values.

abs

Returns the absolute (magnitude) of the complex value.

r, i

Retrieves the real and imaginary part of the complex value.

ri, ir

Swizzle operators return a complex value with the ordering of the real and imaginary parts as indicated by the name.

\page doc_addon_build Script builder

Path: /sdk/add_on/scriptbuilder/

This class is a helper class for loading and building scripts, with a basic pre-processor
that supports conditional compilation, include directives, pragma directives, and metadata declarations.

By default the script builder resolves include directives by loading the included file
from the relative directory of the file it is included from. If you want to do this in another
way, then you should implement the \ref doc_addon_build_1_1 "include callback" which will
let you process the include directive in a custom way, e.g. to load the included file from
memory, or to support multiple search paths. The include callback should call the AddSectionFromFile or
AddSectionFromMemory to include the section in the current build.

If the application should to support pragma directives, it must register the \ref doc_addon_build_1_2 "pragma callback"
to process the text provided for the pragma directive. Without the callback the script builder will give an error
when encountering a pragma directive.

The script builder will also remove any lines that start with <tt>#!</tt> as comments. This is done
to support shebang interpreter directives often used on Linux and UNIX based operative systems.

If you do not want process metadata then you can compile the add-on with the define
AS_PROCESS_METADATA 0, which will exclude the code for processing this. This define
can be made in the project settings or directly in the header.

\section doc_addon_build_1 Public C++ interface

\code
class CScriptBuilder
{
public:
  // Start a new module
  int StartNewModule(asIScriptEngine *engine, const char *moduleName);

  // Load a script section from a file on disk
  // Returns  1 if the file was included
  //          0 if the file had already been included before
  //         <0 on error
  int AddSectionFromFile(const char *filename);

  // Load a script section from memory
  // Returns  1 if the section was included
  //          0 if a section with the same name had already been included before
  //         <0 on error
  int AddSectionFromMemory(const char *sectionName,
                           const char *scriptCode,
                           unsigned int scriptLength = 0,
                           int lineOffset = 0);

  // Build the added script sections
  int BuildModule();

  // Returns the script engine
  asIScriptEngine *GetEngine();

  // Returns the current module
  asIScriptModule *GetModule();

  // Register the callback for resolving include directive
  void SetIncludeCallback(INCLUDECALLBACK_t callback, void *userParam);

  // Register the callback for resolving pragma directive
  void SetPragmaCallback(PRAGMACALLBACK_t callback, void *userParam);

  // Add a pre-processor define for conditional compilation
  void DefineWord(const char *word);

  // Enumerate included script sections
  unsigned int GetSectionCount() const;
  string       GetSectionName(unsigned int idx) const;

  // Get metadata declared for classes, interfaces, and enums
  // Each metadata block, i.e. [...], is returned as a separate string
  std::vector<std::string> GetMetadataStringForType(int typeId);

  // Get metadata declared for functions
  // Each metadata block, i.e. [...], is returned as a separate string
  std::vector<std::string> GetMetadataStringForFunc(asIScriptFunction *func);

  // Get metadata declared for global variables
  // Each metadata block, i.e. [...], is returned as a separate string
  std::vector<std::string> GetMetadataStringForVar(int varIdx);

  // Get metadata declared for a class method
  // Each metadata block, i.e. [...], is returned as a separate string
  // Use the asIScriptFunction for the virtual method for lookup
  std::vector<std::string> GetMetadataStringForTypeMethod(int typeId, asIScriptFunction *method);

  // Get metadata declared for a class property
  // Each metadata block, i.e. [...], is returned as a separate string
  std::vector<std::string> GetMetadataStringForTypeProperty(int typeId, int varIdx);
};
\endcode

\subsection doc_addon_build_1_1 The include callback signature

\code
// This callback will be called for each #include directive encountered by the
// builder. The callback should call the AddSectionFromFile or AddSectionFromMemory
// to add the included section to the script. If the include cannot be resolved
// then the function should return a negative value to abort the compilation.
typedef int (*INCLUDECALLBACK_t)(const char *include, const char *from, CScriptBuilder *builder, void *userParam);
\endcode

\subsection doc_addon_build_1_2 The pragma callback signature

\code
// This callback will be called for each #pragma directive encountered by the builder.
// The application can interpret the pragmaText and decide what do to based on that.
// If the callback returns a negative value the builder will report an error and abort the compilation.
typedef int(*PRAGMACALLBACK_t)(const std::string &pragmaText, CScriptBuilder &builder, void *userParam);
\endcode

\section doc_addon_build_2 Include directives

Example script with include directive:

  \#include "commonfuncs.as"

  void main()
  {
    // Call a function from the included file
    CommonFunc();
  }

\section doc_addon_build_condition Conditional programming

The builder supports conditional programming through the \#if/\#endif preprocessor directives.
The application may define a word with a call to DefineWord(), then the scripts may check
for this definition in the code in order to include/exclude parts of the code.

This is especially useful when scripts are shared between different binaries, for example, in a
client/server application.

Example script with conditional compilation:

  class CObject
  {
    void Process()
    {
  \#if SERVER
      // Do some server specific processing
  \#endif

  \#if CLIENT
      // Do some client specific processing
  \#endif

      // Do some common processing
    }
  }

\section doc_addon_build_metadata Metadata in scripts

Metadata can be added before script class, interface, function, and global variable
declarations. The metadata is removed from the script by the builder class and stored
for post build lookup by the type id, function id, or variable index.

Exactly what the metadata looks like is up to the application. The builder class doesn't
impose any rules, except that the metadata should be added between brackets []. After
the script has been built the application can obtain the metadata strings and interpret
them as it sees fit. Multiple metadata blocks, i.e. [], can be defined for each entity.

Example script with metadata:

  [factory func = CreateOgre]
  class COgre
  {
    [editable]
    vector3 myPosition;

    [editable]
    [range [10, 100]]
    int     myStrength;
  }

  [factory]
  COgre \@CreateOgre()
  {
    return \@COgre();
  }

Example usage:

\code
CScriptBuilder builder;
int r = builder.StartNewModule(engine, "my module");
if( r >= 0 )
  r = builder.AddSectionFromMemory(script);
if( r >= 0 )
  r = builder.BuildModule();
if( r >= 0 )
{
  // Find global variables that have been marked as editable by user
  asIScriptModule *mod = engine->GetModule("my module");
  int count = mod->GetGlobalVarCount();
  for( int n = 0; n < count; n++ )
  {
    vector<string> metadata = builder.GetMetadataStringForVar(n);
    for( int m = 0; m < metadata.size(); m++ )
    {
      if( metadata[m] == "editable" )
      {
        // Show the global variable in a GUI
        ...
      }
    }
  }
}
\endcode

\page doc_addon_autowrap Automatic wrapper functions

Path: /sdk/add_on/autowrapper/aswrappedcall.h

This header file declares some macros and template functions that will let the application developer
automatically generate wrapper functions using the \ref doc_generic "generic calling convention" with
a simple call to a preprocessor macro. This is useful for those platforms where the native calling
conventions are not yet supported.

The macros are defined as:

\code
// Wrap a global function with implicit or explicit signature
#define WRAP_FN(name)
#define WRAP_FN_PR(name, Parameters, ReturnType)

// Wrap a class method with implicit or explicit signature
#define WRAP_MFN(ClassType, name)
#define WRAP_MFN_PR(ClassType, name, Parameters, ReturnType)

// Wrap a class method that will emulate a global function
#define WRAP_MFN_GLOBAL(ClassType, name)
#define WRAP_MFN_GLOBAL_PR(ClassType, name, Parameters, ReturnType)

// Wrap a global function that will emulate a class method and receives the 'this' pointer as the first argument
#define WRAP_OBJ_FIRST(name)
#define WRAP_OBJ_FIRST_PR(name, Parameters, ReturnType)

// Wrap a global function that will emulate a class method and receives the 'this' pointer as the last argument
#define WRAP_OBJ_LAST(name)
#define WRAP_OBJ_LAST_PR(name, Parameters, ReturnType)

// Wrap a constructor with an explicit signature
#define WRAP_CON(ClassType, Parameters)

// Wrap a destructor
#define WRAP_DES(ClassType)
\endcode

As you can see they are very similar to the \ref doc_register_func_1 "asFUNCTION" and
\ref doc_register_func_1 "asMETHOD" macros,  and are used the same way.

Unfortunately the template functions needed to perform this generation are quite complex and older
compilers may not be able to handle them. One such example is Microsoft Visual C++ 6, though luckily
it has no need for them as AngelScript already supports native calling conventions for it.

\section doc_addon_autowrap_1 Example usage

\code
#include "aswrappedcall.h"

// The application function that we want to register
void DoSomething(std::string param1, int param2);

// Registering the wrapper with AngelScript
void RegisterWrapper(asIScriptEngine *engine)
{
  int r;

  // The WRAP_FN macro automatically implements and returns the function pointer of the generic wrapper
  // function. Observe, that the calling convention should be set as asCALL_GENERIC in this case.
  r = engine->RegisterGlobalFunction("void DoSomething(string, int)", WRAP_FN(DoSomething), asCALL_GENERIC); assert( r >= 0 );
}
\endcode

\section doc_addon_autowrap_2 Adding support for more parameters

The aswrappedcall.h header file is by default prepared to support functions with up to 4 arguments.
If you have a need for more arguments then you can use the generator that you find in the sub-directory
to prepare a new header file.

Open the generateheader.cpp in an editor and set the max_args variable to the number of arguments you need
and then compile and run the code. It will print the new header file to the standard output so you just need
to direct this to a file.

\page doc_addon_helpers_try Exception routines

Path: /sdk/add_on/scripthelper/

The exception handling routines are registered by the application
with a call to RegisterExceptionRoutines.

\section doc_addon_helpers_try_1 Public C++ interface

\code
// Register the exception routines.
//  'void throw(const string &msg)'
//  'string getExceptionInfo()'
void RegisterExceptionRoutines(asIScriptEngine *engine);
\endcode

\section doc_add_helpers_try_2 Public script interface

\see \ref doc_script_stdlib_exception

\page doc_addon_helpers Helper functions

Path: /sdk/add_on/scripthelper/

These helper functions simplify the implementation of common tasks. They can be used as is
or can serve as the starting point for your own framework.

\section doc_addon_helpers_1 Public C++ interface

\code
// Compare relation between two objects of the same type.
// Uses the object's opCmp method to perform the comparison.
// Returns a negative value if the comparison couldn't be performed.
int CompareRelation(asIScriptEngine *engine, void *leftObj, void *rightObj, int typeId, int &result);

// Compare equality between two objects of the same type.
// Uses the object's opEquals method to perform the comparison, or if that doesn't exist the opCmp method.
// Returns a negative value if the comparison couldn't be performed.
int CompareEquality(asIScriptEngine *engine, void *leftObj, void *rightObj, int typeId, bool &result);

// Compile and execute simple statements.
// The module is optional. If given the statements can access the entities compiled in the module.
// The caller can optionally provide its own context, for example if a context should be reused.
int ExecuteString(asIScriptEngine *engine, const char *code, asIScriptModule *mod = 0, asIScriptContext *ctx = 0);

// Compile and execute simple statements with option of return value.
// The module is optional. If given the statements can access the entities compiled in the module.
// The caller can optionally provide its own context, for example if a context should be reused.
int ExecuteString(asIScriptEngine *engine, const char *code, void *ret, int retTypeId, asIScriptModule *mod = 0, asIScriptContext *ctx = 0);

// Format the details of the script exception into a human readable text.
// Whenever the asIScriptContext::Execute method returns asEXECUTION_EXCEPTION, the application
// can call this function to get more information about that exception in a human readable form.
// The information obtained includes the current function, the script source section,
// program position in the source section, and the exception description itself.
std::string GetExceptionInfo(asIScriptContext *ctx, bool showStack = false);

// Write registered application interface to file.
// This function creates a file with the configuration for the offline compiler, asbuild, in the samples.
// If you wish to use the offline compiler you should call this function from you application after the
// application interface has been fully registered. This way you will not have to create the configuration
// file manually.
int WriteConfigToFile(asIScriptEngine *engine, const char *filename);

// Write the registered application interface to a text stream.
int WriteConfigToStream(asIScriptEngine *engine, std::ostream &strm);

// Loads an interface from a text stream and configures the engine with it. This will not
// set the correct function pointers, so it is not possible to use this engine to execute
// scripts, but it can be used to compile scripts and save the byte code.
int ConfigEngineFromStream(asIScriptEngine *engine, std::istream &strm, const char *nameOfStream = "config", asIStringFactory *stringFactory = 0);
\endcode

\section doc_addon_helpers_2 Example

To compare two script objects the application can execute the following code:

\code
void Compare(asIScriptObject *a, asIScriptObject *b)
{
  asIScriptEngine *engine = a->GetEngine();
  int typeId = a->GetTypeId();

  int cmp;
  int r = CompareRelation(engine, a, b, typeId, cmp);
  if( r < 0 )
  {
    cout << "The relation between a and b cannot be established b" << endl;
  }
  else
  {
    if( cmp < 0 )
      cout << "a is smaller than b" << endl;
    else if( cmp == 0 )
      cout << "a is equal to b" << endl;
    else
      cout << "a is greater than b" << endl;
  }
}
\endcode

*/

repo_name: Antidote/openrpgeditor

license: mit


code:
/**

\page doc_adv_access_mask Access masks and exposing different interfaces

An application may need to expose different interfaces to different types of scripts,
e.g. a game entity may only have access to specific set of functions, while the GUI
script can have access to a completely different set of functions.

To accomplish this the application can set a bitmask while registering the interface,
and then use that bitmask when building the scripts to determine what the scripts
should or should not be able to access.

\code
void ConfigureEngine(asIScriptEngine *engine)
{
  // Register the interface available to script type 1
  engine->SetDefaultAccessMask(0x1);
  r = engine->RegisterGlobalFunction("void func1()", asFUNCTION(func1), asCALL_CDECL); assert( r >= 0 );

  // Register the interface available to script type 2
  engine->SetDefaultAccessMask(0x2);
  r = engine->RegisterGlobalFunction("void func2()", asFUNCTION(func2), asCALL_CDECL); assert( r >= 0 );

  // Register the interface available to both script types
  engine->SetDefaultAccessMask(0x3);
  r = engine->RegisterGlobalFunction("void func3()", asFUNCTION(func3), asCALL_CDECL); assert( r >= 0 );
}

int CompileScript(asIScriptEngine *engine, const char *script, int type)
{
  int r;
  CScriptBuilder builder;
  r = builder.StartNewModule(engine, script);
  if( r < 0 ) return r;

  // Set the access mask for the module, which will
  // determine the functions from the application
  // interface that can be called
  asIScriptModule *mod = builder.GetModule();
  mod->SetAccessMask(type);

  // Add the script section and build the script
  r = builder.AddSectionFromFile(script);
  if( r < 0 ) return r;

  return builder.BuildModule();
}
\endcode

The access mask can be defined for the following entities in the application interface:

 - \ref asIScriptEngine::RegisterGlobalFunction "Global functions"
 - \ref asIScriptEngine::RegisterGlobalProperty "Global properties"
 - \ref asIScriptEngine::RegisterObjectType "Object types"
 - \ref asIScriptEngine::RegisterObjectMethod "Individual methods of types"
 - \ref asIScriptEngine::RegisterObjectProperty "Individual properties of types"
 - \ref asIScriptEngine::RegisterObjectBehaviour "Individual object behaviours"

*/


code:
/**

\page doc_adv_class_hierarchy Class hierarchies

AngelScript cannot automatically determine relationships between registered classes, so in
order to establish the hierarchies for use within the script language it is necessary
to do a bit more registration beyond the normal \ref doc_register_type "object registration".

Hierarchies can currently only be registered for \ref doc_reg_basicref "reference types",
not for \ref doc_register_val_type "value types".

\section doc_adv_class_hierarchy_1 Establishing the relationship

In order to let AngelScript know that two types are related you need to register the
reference cast operators \ref doc_script_class_conv "opCast" and \ref doc_script_class_conv "opImplCast". The
opCast should be used if you only want to allow the cast through an explicit
call with the <tt>\ref conversion "cast<class>"</tt> operator. opImplCast
should be used when you want to allow the compiler to implicitly perform the cast as necessary.

Usually you'll want to use opImplCast for casts from a derived type to the base type,
and opCast for casts from a base type to a derived type.

\code
// Example opCast behaviour
template<class A, class B>
B* refCast(A* a)
{
    // If the handle already is a null handle, then just return the null handle
    if( !a ) return 0;

    // Now try to dynamically cast the pointer to the wanted type
    B* b = dynamic_cast<B*>(a);
    if( b != 0 )
    {
        // Since the cast was made, we need to increase the ref counter for the returned handle
        b->addref();
    }
    return b;
}

// Example registration of the behaviour
r = engine->RegisterObjectMethod("base", "derived@ opCast()", asFUNCTION((refCast<base,derived>)), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("derived", "base@ opImplCast()", asFUNCTION((refCast<derived,base>)), asCALL_CDECL_OBJLAST); assert( r >= 0 );

// Also register the const overloads so the cast works also when the handle is read only
r = engine->RegisterObjectMethod("base", "const derived@ opCast() const", asFUNCTION((refCast<base,derived>)), asCALL_CDECL_OBJLAST); assert( r >= 0 );
r = engine->RegisterObjectMethod("derived", "const base@ opImplCast() const", asFUNCTION((refCast<derived,base>)), asCALL_CDECL_OBJLAST); assert( r >= 0 );
\endcode

Note that it may be necessary to add extra parenthesis to the <tt>asFUNCTION</tt> macro so that the preprocessor
doesn't interpret the <tt>,</tt> in the template declaration as the argument separator in the macro.

\section doc_adv_class_hierarchy_2 Inherited methods and properties

Just as relationships cannot be determined, there is also no way to automatically let AngelScript
add inherited methods and properties to derived types. The reason for this is that method pointers
and property offsets may differ between the base class and derived class, especially when multiple
inheritance is used, and there is no way to automatically determine exactly what the difference is.

For this reason the application needs to register all the inherited methods and properties for
the derived classes, which may lead to a bit of duplicate code. However, you may be able to avoid
the duplication through a bit of clever thinking. Here is an example of registering the methods and
properties for a base class and the derived class (registration of behaviours has been omitted for briefness):

Observe that this way of doing it is not possible if the derived type hides members of the base type.
If this is the case, then there is no option but to register each visible member in the derived type explicitly,
excluding the hidden members of the base type.

\code
// The base class
class base
{
public:
  virtual void aMethod();

  int aProperty;
};

// The derived class
class derived : public base
{
public:
  virtual void aNewMethod();

  int aNewProperty;
};

// The code to register the classes
// This is implemented as a template function, to support multiple inheritance
template <class T>
void RegisterBaseMembers(asIScriptEngine *engine, const char *type)
{
  int r;

  r = engine->RegisterObjectMethod(type, "void aMethod()", asMETHOD(T, aMethod), asCALL_THISCALL); assert( r >= 0 );

  r = engine->RegisterObjectProperty(type, "int aProperty", asOFFSET(T, aProperty)); assert( r >= 0 );
}

template <class T>
void RegisterDerivedMembers(asIScriptEngine *engine, const char *type)
{
  int r;

  // Register the inherited members by calling
  // the registration of the base members
  RegisterBaseMembers<T>(engine, type);

  // Now register the new members
  r = engine->RegisterObjectMethod(type, "void aNewMethod()", asMETHOD(T, aNewMethod), asCALL_THISCALL); assert( r >= 0 );

  r = engine->RegisterObjectProperty(type, "int aNewProperty", asOFFSET(T, aNewProperty)); assert( r >= 0 );
}

void RegisterTypes(asIScriptEngine *engine)
{
  int r;

  // Register the base type
  r = engine->RegisterObjectType("base", 0, asOBJ_REF); assert( r >= 0 );
  RegisterBaseMembers<base>(engine, "base");

  // Register the derived type
  r = engine->RegisterObjectType("derived", 0, asOBJ_REF); assert( r >= 0 );
  RegisterDerivedMembers<derived>(engine, "derived");
}
\endcode

*/


code:
/**

\page doc_adv_concurrent Concurrent scripts

The script engine can run multiple scripts in parallel, i.e. concurrent scripts. This can be done easily
using \ref doc_adv_multithread "multithreading" where each thread runs its own script context, but this article
is going to explain how it is done without multithreading.

In order to execute multiple scripts in parallel, each script must have it's own \ref asIScriptContext, where
the context is set up as for a \ref doc_call_script_func "normal function call". Then the application needs to
set a timeout for each context. When the timeout is reached, the context should be \ref asIScriptContext::Suspend
"suspended", so that the next context can execute for a while.

Here's a very simple example of how this can be done:

\code
// The contexts have already been prepared before this function is called
void ExecuteScripts(std::vector<asIScriptContext *> contexts)
{
  // This function will run until all scripts have completed
  while( contexts.size() > 0 )
  {
    for( asUINT n = 0; n < contexts.size(); n++ )
    {
      // Set a 10 millisecond timeout for this context
      SetTimeoutForContext(contexts[n], 10);

      // Resume the execution of this context by calling Execute
      int r = contexts[n]->Execute();

      // Remove the timeout so it won't be triggered accidentally
      RemoveTimeoutForContext();

      // Determine if the script completed, or was timed out
      if( r == asEXECUTION_SUSPENDED )
      {
        // The script will continue in the next iteration
      }
      else
      {
        // The script has completed the execution, so we take it out of the list of scripts
        contexts[n--] = contexts.back();
        contexts.pop_back();
      }
    }
  }
}
\endcode

The application can manage the execution of the scripts in a simple round-robin fashion, where each script gets
equal amount of execution time, or a more intricate management algorithm can be built, e.g. to give more execution
time to high priority scripts etc.

The time out function, i.e. SetTimeoutForContext in the example above, can be implemented in two different ways.
Through the use of \ref asIScriptContext::SetLineCallback "line callbacks", where the context will invoke the callback for
each statement in the script. The callback can then check if the timeout limit has been reached and suspend the context.

The other way is through the use of a timeout thread, where the thread simply sleeps until the timeout limit has been reached,
and when the thread wakes up it suspends the context (if it is still running).

The timeout thread is probably the easiest to implement, and also doesn't impact the performance as much as the line
callback. The line callback may still have to be used if the target OS doesn't support multithreading though.

Here's a simple example of how to implement the timeout function with a separate thread:

\code
static HANDLE            thread_handle = 0;
static asIScriptContext *thread_ctx;

DWORD WINAPI TimeoutThread(void *sleeptime)
{
  Sleep(*reinterpret_cast<int*>(sleeptime));
  if( thread_ctx )
    thread_ctx->Suspend();

  return 0;
}

void SetTimeoutForContext(asIScriptContext *ctx, int milliseconds)
{
  thread_ctx    = ctx;
  thread_handle = CreateThread(0, 50, TimeoutThread, reinterpret_cast<void*>(&milliseconds), 0, 0);
}

void RemoveTimeoutForContext()
{
  // TerminateThread should be used with extreme care, but in this
  // case the TimeoutThread can't do any harm even if interrupted
  // in the middle of the execution
  TerminateThread(thread_handle, 0);
  thread_handle = 0;
}
\endcode

Observe that the routines for multithreading usually differ a lot depending on the target system. The above code
is for Windows and will most likely require adaption to work on any other system.

\see \ref doc_addon_ctxmgr, \ref doc_samples_concurrent, \ref doc_adv_coroutine

*/


code:
/**

\page doc_adv_coroutine Co-routines

Co-routines is a way to allow multiple execution paths in parallel, but without the hazards of pre-emptive scheduling in
\ref doc_adv_concurrent "multithreading" where one thread can be suspended at any moment so another can resume. Because co-routines always voluntarily
suspend themselves in favor of the next co-routine, there is no need to worry about atomic instructions and critical sections.

Co-routines are not natively built-into the AngelScript library, but it can easily be implemented from the application side.
In fact, the \ref doc_addon_ctxmgr add-on already provides a default implementation for this.

To implement your own version of co-routines you will need a couple of pieces:

 - The co-routine itself, which is just an instance of the \ref asIScriptContext object. Each co-routine will have its own
   context object that holds the callstack of the co-routine.
 - A function that will permit the script to create, or spawn, new co-routines. This function will need to be able to refer
   to starting function of the new co-routine. This reference can be done by name, or perhaps more elegantly with a
   \ref doc_datatypes_funcptr "function pointer". Once invoked this function will instanciate the new context, and prepare
   it with the starting function.
 - A function that will permit a co-routine to yield control to the next co-routine. This function will simply suspend the
   current context so the next co-routine can be resumed.
 - A simple control algorithm for the co-routines. This can just be a loop that will iterate over an array of co-routines,
   i.e. contexts, until all of them have finished executing. When a new co-routine is created it is simply appended to the
   array to be picked up when the current co-routine yields the control.

A simple implementation of the function that spawns a new co-routine may look like this:

\code
void CreateCoRoutine(string &func)
{
  asIScriptContext *ctx = asGetActiveContext();
  if( ctx )
  {
    asIScriptEngine *engine = ctx->GetEngine();
    string mod = ctx->GetFunction()->GetModuleName();

    // We need to find the function that will be created as the co-routine
    string decl = "void " + func + "()";
    asIScriptFunction *funcPtr = engine->GetModule(mod.c_str())->GetFunctionByDecl(decl.c_str());
    if( funcPtr == 0 )
    {
      // No function could be found, raise an exception
      ctx->SetException(("Function '" + decl + "' doesn't exist").c_str());
      return;
    }

    // Create a new context for the co-routine
    asIScriptContext *coctx = engine->CreateContext();
    coctx->Prepare(funcPtr);

    // Add the new co-routine context to the array of co-routines
    coroutines.push_back(coctx);
  }
}
\endcode

The yield function is even simpler:

\code
void Yield()
{
  asIScriptContext *ctx = asGetActiveContext();
  if( ctx )
  {
    // Suspend the context so the next co-routine can be resumed
    ctx->Suspend();
  }
}
\endcode

A basic control algorithm might look like this:

\code
std::vector<asIScriptContext *> coroutines;
void Execute()
{
  int n = 0;
  while( coroutines.size() > 0 )
  {
    // Resume the co-routine
    int r = coroutines[n]->Execute();
    if( r == asEXECUTION_SUSPENDED )
    {
      // Resume the next co-routine
      if( ++n == coroutines.size() )
        n = 0;
    }
    else
    {
      // The co-routine finished so let's remove it
      coroutines[n]->Release();
      coroutines.erase(n);
    }
  }
}
\endcode

\see \ref doc_addon_ctxmgr, \ref doc_samples_corout, \ref doc_adv_concurrent

*/


code:
/**

\page doc_adv_custom_options Custom options

Most applications have different needs and AngelScript is meant to be as flexible
as possible to suit everybody. For this reason there are several options for
customizing the script engine for the best fit.

\section doc_adv_custom_options_reg_types Registerable types

Even types that one might normally expect to be built-in to a script language, e.g.
string, array, and other container classes, are \ref doc_register_type "registered by the application".
This is to allow the application to provide the exact implementation desired.

Of course, should the application developer want to use a premade implementation the
\ref doc_addon_script "add-ons provide just that".

\section doc_adv_custom_options_lang_mod Language modifications

The engine method \ref asIScriptEngine::SetEngineProperty "SetEngineProperty" permits making
runtime choices about several different behaviours in the engine.

The following modify the script language in one way or the other:

\ref asEP_DISALLOW_EMPTY_LIST_ELEMENTS

By turning on this option the compiler will no longer accept empty list elements in initialization lists.
The following will for example not be supported:

<pre>
  array<int> arr = {1,2,,4,5,};
</pre>

When not turned on, the compiler will leave the empty list elements with the uninitialized value, just as an
uninitialized variable of the same type.

\ref asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE

By turning on this the compiler will no longer allow the use of value assignment operators on reference types.
While it may seem drastic, it can help reduce risk for bugs in the scripts, as the script writer will no longer
be able to do a value assignment by mistake when he meant to a handle assignment. Reference types should usually
not be copied, so the imposed restriction will likely not cause problems anyway.

\ref asEP_ALLOW_UNSAFE_REFERENCES

By turning on unsafe references you allow in-out references to be used for primitives and value types too.
Normally this will work fine, just as it does in ordinary languages such as C++, but know that it is
quite possible to write scripts that will cause memory invasions or crashes if the references are not properly
guarded. With this option turned on you cannot consider the scripts to be sand-boxed any longer.

Turning this option on also makes temporary objects created within expressions to be destroyed only at the
end of expressions, rather than as soon as possible. This makes it possible to pass references to temporary objects
to function calls within the expression, without the references becoming invalid too early.

\ref asEP_USE_CHARACTER_LITERALS, \ref asEP_ALLOW_MULTILINE_STRINGS, \ref asEP_SCRIPT_SCANNER, \ref asEP_STRING_ENCODING

These options are used to determine how strings are treated by the compiler. The details are described in \ref doc_strings.

\ref asEP_HEREDOC_TRIM_MODE

With this option the compiler can be set to always trim \ref doc_datatypes_strings "heredoc strings",
only trim if it is multiple lines, or never trim them.

\ref asEP_ALLOW_IMPLICIT_HANDLE_TYPES

This option is experimental. By turning it on script classes can be declared to always be treated as handles by declaring the
class with @ before the name of the class. When this is done all variables of that type will be handles, and the assignment
operator will always perform a handle assignment.

\ref asEP_REQUIRE_ENUM_SCOPE

With this option all enum values must be prefixed with the enum type using the scope operator to qualify.

\ref asEP_PROPERTY_ACCESSOR_MODE

By default \ref doc_script_class_prop "virtual property accessors" when declared as individual functions need to be
marked as such with the keyword 'property', or else the compiler won't consider the functions as virtual properties.
This behaviour was introduced in version 2.33.1.

Before this version, the compiler would automatically identify functions with the pre-fix 'get_' or 'set_' as virtual
property accessors if the function signature was appropriate. This led to undesired behaviour when developers would
declare such functions without the intention of them being used as virtual properties and yet the compiler used them as such.

For backwards compatibility it is still possible to configure the engine to use this behaviour by setting the engine
property asEP_PROPERTY_ACCESSOR_MODE to 2.

It is also possible to disable virtual property accessors all together by setting the engine property to 0.

Setting the option to 1 only allows virtual property accessors for registered functions, but still without requiring the keyword 'property'.

\ref asEP_DISALLOW_GLOBAL_VARS

The application can disable the ability to declare global variables in scripts completely. This can be useful in such cases
when the application wish to have full control of what can and cannot be stored by a script.

\ref asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT

This property determines if the compiler will automatically provide a default constructor for classes. When set to 0 (default)
it will be as per \ref doc_script_class_construct_auto "language specification". When set to 1 it will always be generated, and
when set to 2 it will never be generated.

\ref asEP_ALWAYS_IMPL_DEFAULT_COPY_CONSTRUCT

This property determines if the compiler will automatically provide a copy constructor for classes. When set to 0 (default)
it will be as per \ref doc_script_class_construct_auto "language specification". When set to 1 it will always be generated, and
when set to 2 it will never be generated.

In versions before 2.37.0 the copy constructor was not generated automatically, so if backwards compatibility is needed, set this to 0.

\ref asEP_ALWAYS_IMPL_DEFAULT_COPY

This property determines if the compiler will automatically provide a copy operator for classes. When set to 0 (default)
it will be as per \ref doc_script_class_assign_ops_auto "language specification". When set to 1 it will always be generated, and
when set to 2 it will never be generated.

In versions before 2.37.0 the copy operator was always generated automatically, so if backwards compatibility is needed, set this to 1.

\ref asEP_ALTER_SYNTAX_NAMED_ARGS

If this flag is set to 1 or 2 the compiler will accept the '=' instead of ':' for \ref function "naming arguments in function calls".
When option 1 is used the compiler will warn about it, so the script writer can update the script to the correct ':' token. When
option 2 is used both '=' and ':' are accepted silently.

Observe that the use of the '=' token for naming arguments may cause a bit of a confusion. Especially if there is a variable
with the same name as the function argument as the script writer may think he's updating the value of the variable, but is
just naming the function argument.

\ref asEP_DISABLE_INTEGER_DIVISION

This option changes the default behaviour of the / and /= operators. When true, this option replaces integer division
with floating-point division, e.g. 1/2 == 0.5 instead of 1/2 == 0

\ref asEP_PRIVATE_PROP_AS_PROTECTED

When this option is set to true the compiler will not prevent the access to private properties inherited from the parent class.
It will only write a warning.

This option is provided to give backwards compatibility for scripts written between versions 2.19.1, when support for private
properties was added, albeit working more like protected properties, and version 2.30.0 when the behaviour was changed so that private
properties work like in other languages, i.e. they can't be accessed by derived classes.

\ref asEP_ALLOW_UNICODE_IDENTIFIERS

When this option is set to true the compiler will accept identifiers that contain characters with byte
value higher than 127. This permits the use of international characters in the identifiers as the script
can be encoded in UTF-8 format and compiler normally.

\ref asEP_IGNORE_DUPLICATE_SHARED_INTF

By turning on this option the compiler will silently accept duplicate declarations of shared interfaces in modules.
This option was added to provide backwards compatibility with 2.35.0.

\todo document asEP_BOOL_CONVERSION_MODE

\todo document asEP_FOREACH_SUPPORT

\section doc_adv_custom_options_engine Engine behaviours

There are also several options in \ref asIScriptEngine::SetEngineProperty "SetEngineProperty" for modifying the way the engine behaves.

\ref asEP_MAX_NESTED_CALLS

This property defines how many recursive nested calls the engine should accept. In this context a nested call is when a script calls into
an application registered function that in turn calls another script function. The second call is then said to be a nested call.

By default the engine will accept 100 nested calls.

\ref asEP_OPTIMIZE_BYTECODE

Normally this option is only used for testing the library, but should you find that the compilation time takes too long, then
it may be of interest to turn off the bytecode optimization pass by setting this option to false.

\ref asEP_COPY_SCRIPT_SECTIONS

If you want to spare some dynamic memory and the script sections passed to the engine is already stored somewhere in memory then you
can turn off this options. If you do you'll need to be careful not to modify or deallocate the script sections until module has been built.

\ref asEP_MAX_STACK_SIZE, \ref asEP_INIT_STACK_SIZE, \ref asEP_MAX_CALL_STACK_SIZE, \ref asEP_INIT_CALL_STACK_SIZE

The script context's data stack grows dynamically as needed during executions. By default there is no limit to how large it may grow, but
if you wish to set this limit you can do with the asEP_MAX_STACK_SIZE option. The limit is given in bytes, but it is only an approximate limit. Setting the
limit to 1MB doesn't mean the stack will grow exactly to 1MB, but you can be certain that it will not grow much beyond that.

Whenever a context attempts to grow the stack more than it is allowed, it will abort the execution and return a 'stack overflow' script
exception.

Similarly the call stack also grows dynamically as needed during executions. The default here is also no limit, with the ability to limit
maximum size by setting the asEP_MAX_CALL_STACK_SIZE. This limit is set in number of function calls.

In some cases it may be useful to set the initial stack size too, e.g. if you know beforehand that a large stack is needed, or
if you wish to avoid any runtime memory allocations during an execution. In this case you can use the asEP_INIT_STACK_SIZE for the
data stack, and asEP_INIT_CALL_STACK_SIZE for the call stack.

\ref asEP_BUILD_WITHOUT_LINE_CUES

This option can be used to speed up the execution of scripts a bit. It is best described in \ref doc_finetuning_3.

\ref asEP_INIT_GLOBAL_VARS_AFTER_BUILD

By default the global variables in the script modules are initialized immediately after building the scripts, but sometimes this is not
desired. For example, if you debug the initialization of the variables, or if you're building an offline compiler, or even if you want
to add extra validation of the variables to make sure the script doesn't declare any variables you don't want it to.

\see \ref doc_adv_precompile

\ref asEP_INCLUDE_JIT_INSTRUCTIONS

In order for JIT compilation to work properly it needs to have some hints in the bytecode so it can know where a switch from
bytecode execution to JIT compiled execution shall be done. By default this option is turned off as it would just add an overhead
to the bytecode, but when using JIT compilation this overhead will be compensated by the faster execution with direct machine code.

\see \ref doc_adv_jit

\ref asEP_EXPAND_DEF_ARRAY_TO_TMPL

This option is to determine how the \ref asIScriptEngine::RegisterDefaultArrayType "default array type" is displayed in compiler
messages and function declarations, e.g. int[] or array<int>.

\ref asEP_AUTO_GARBAGE_COLLECT

By default AngelScript's incremental garbage collector is executed as scripts are invoked by the application. This does add
a slight overhead to the execution, which is normally tolerable but in some applications the CPU cycles may be needed for other
things. In this case the automatic execution of the garbage collector can be turned off to hold off on the execution until the
CPU can be spared.

\see \ref doc_gc

\ref asEP_DISABLE_SCRIPT_CLASS_GC

By default the script compiler will detect script classes that can potentially form circular references and will flag them for
garbage detection. If it is known that no circular references are formed, or if they are manually resolved in the script, it is
possible to disable this to increase performance.

\see \ref doc_gc

\ref asEP_COMPILER_WARNINGS

Compiler warnings can be turned off or treated as errors by setting this engine property.

\ref asEP_GENERIC_CALL_MODE

By default the \ref doc_generic "generic calling convention" treats the ref counts in the handles the same way that the native calling convention, i.e.
releases any handles passed to a function if they have been marked as auto handles, and increments the returned handle if it has
been marked as auto handle.

If the behaviour used before 2.33.0 is desired for backwards compatibility, then set this property to 0. In this case the
generic calling convention will always release references for handles received in arguments, and never increment references
for returned handles.

\ref asEP_NO_DEBUG_OUTPUT

When the library is built with AS_DEBUG it will write debug output to the folder AS_DEBUG by default. By turning on this engine property this debug output is disabled.

*/


code:
/**

\page doc_adv_dynamic_build Dynamic compilations

There are various forms of dynamic compilations of scripts. In the following subtopics
I try to explain the theory of them and give some information on how they can be implemented.

\section doc_adv_dynamic_build_ondemand On demand builds

The most common form of dynamic compilations is building new modules on demand, i.e.
as they are needed. When using this the application or game engine is typically designed
to have separate scripts to perform different tasks, e.g. menu handling, different types of AI
controllers, player controller, etc. If these separate scripts have an abstraction layer through
the application to interact with each other it is very easy to build the scripts on demand.

To build a new script on demand, simply get a new module, add the needed script sections
to it and build it just as you would when \ref doc_compile_script "building the first script".
As each module is independent the previously existing module will be unaffected.

Each module can be configured to see a \ref doc_adv_access_mask "different application interface",
so there is no need to create different engine instances.

Though modules are independent, they can still interact with each other if the application
provides the interface for that. To make the communication between modules easier one can
chose to use \ref doc_script_shared "shared script entities". Shared script entities will
be compiled only once by the first module that includes the code. Any subsequent module that
also include the code for the shared entity will reuse what was built by the first module, i.e.
will share the internal type and bytecode.

Another option is to \ref doc_global_import "import global functions" from a previously
compiled module. In this case the application must make sure the function that exports the
functions is compiled first, then after building the module that imports the function the
application must call the \ref asIScriptModule::BindAllImportedFunctions so conclude the imports.

\see \ref doc_samples_game "Game sample"

\section doc_adv_dynamic_build_incr Incremental builds

Besides the ordinary \ref doc_compile_script "compilation of scripts" and subsequent
\ref doc_call_script_func "executions", AngelScript also support dynamically compiling
additional \ref asIScriptModule::CompileFunction "functions" and
\ref asIScriptModule::CompileGlobalVar "global variables" to incrementally add to the
scope of a module. These functions and variables will become part of the scope, just
as if they had been included in the initial script compilation which means that subsequent
executions or incremental compilations can use them.

It is also possible to dynamically remove \ref asIScriptModule::RemoveFunction "functions"
and \ref asIScriptModule::RemoveGlobalVar "variables". Doing so doesn't immediately discard
the functions or variables, so other functions that still refer to them will not fail when
executing them. They will however no longer be visible for new compilations or when searching
for functions or variables in the module.

This kind of dynamic compilations is most useful when dealing with user interaction,
e.g. an ingame console, or perhaps event handlers, e.g. a trigger on a GUI button click.

\see \ref doc_addon_helpers "ExecuteString() add-on", \ref doc_samples_console "Console sample"

\section doc_adv_dynamic_build_hot Hot reloading scripts

Hot reloading is most often used when quick change & test cycles are wanted. It is quite common
for game engines to have a debug mode that continuously monitors the script files to detect any
updates that are made, and when detected automatically reloads the scripts without restarting
the game. This allows the developers, for example, to quickly change the behaviour of the AI and
immediately see the result without having to play through the entire level over and over again.

Hot reloading without preserving the state of existing objects is quite trivial. Simply discard
everything, reload the scripts, and create new objects. On the other hand, hot reloading scripts
while preserving the state of existing objects can be quite tricky, but is also the most rewarding
when implemented successfully.

The first part to reloading while preserving the state is keeping track of the object instances so
the application knows which objects needs to be serialized when a module is hot reloaded. It is
entirely up to the application to build and maintain this mapping.

The second part is knowing which script files that will trigger a reload when changed. When building
the module the application needs to store the list of the files that were added to it. If you use the
standard \ref doc_addon_build "script builder add-on", then it provides methods to enumerate the included
sections or files.

The third part is the hardest, and that is to implement the actual serialization. Serializing object members
of value types is normally quite trivial, simply \ref doc_adv_reflection_vars "enumerate the object properties"
and store a name-value pair for each. Serializing object members of reference types needs some consideration,
as depending on the object that is referred to, either you will be able to store the actual pointer, or you
will need to store some kind of descriptor as the referred to object will also be recreated during the reload.

Once all the objects that will need to be recreated after the reload have been serialized for backup,
the module can be rebuilt using the normal procedure for \ref doc_compile_script "compiling a script".
Afterwards the serialized objects needs to be recreated. Once created you'll enumerate
the members and set their values or references according to the backed up data.

\subsection doc_adv_dynamic_build_hot_1 Things to consider

 - Design the engine and script interface with hot reloading in mind from the start. Hot reloading is much
   easier to implement the less complex interface you have, e.g. script objects that can only interact with
   other script objects indirectly through the application will not be able to hold references to objects
   unknown by the application.
 - \ref doc_script_shared "Shared script entities" will not be recompiled if some module or existing object
   (including those pending destruction in the garbage collector) still refers to the code. It's recommended
   that you minimize the use of shared entities to where necessary so as to minimize the need to modify them.
 - Before discarding the original objects, consider doing a test compilation of the modified scripts in a
   temporary module first, and only go ahead with the hot reloading if the test compilation is successful. That
   way you can catch compilation errors that would otherwise cause the recreation of the new objects to fail.
 - When recreating object instances you can take advantage of the method
   \ref asIScriptEngine::CreateUninitializedScriptObject to create the objects without actually
   executing the script class constructor, which may have unwanted side effects during the reload.
 - Decide what to do when the script modifications introduces new object properties or removes existing
   properties, as you will not be able to restore the exact same object state then. Perhaps the new property
   can be filled with some default value to allow the continuation of the execution? Or perhaps the script itself
   can have a special event handler to provide the initial value of the new member?
 - The \ref doc_addon_serializer "Serializer" add-on has been implemented to aid the implementation of hot reloading
   scripts, though it may not suit all types of applications.
 - Although it is possible to \ref doc_serialization_contexts "serialize a script context", if any function on the
   context's call stack is modified the program position cannot be reliably restored. Therefore it is recommended
   that you design your application so that contexts can be aborted when hot reloading and any long running scripts
   restarted, or avoid scripts that run over multiple frames all together so that it is guaranteed that no contexts
   are active when hot reloading.

\see \ref doc_addon_serializer, \ref doc_serialization

*/


code:
/**

\page doc_adv_dynamic_config Dynamic configurations

AngelScript supports the concept for configuration groups. This can be used for example by application plug-ins
that wish to register their own interface with the script engine. When the plug-in is later removed, the configuration
group for that plug-in can also be removed from the AngelScript interface without having to reinitialize everything.

To register part of the interface in a configuration group, the registration should be done between calls to
\ref asIScriptEngine::BeginConfigGroup "BeginConfigGroup" and \ref asIScriptEngine::EndConfigGroup "EndConfigGroup".
This can be done as many times as desired, but groups cannot be nested. Observe that object methods, behaviours, and
properties will always be placed in the same group where the object type was placed even if another group has been
specified between the calls.

To remove a configuration group the method \ref asIScriptEngine::RemoveConfigGroup "RemoveConfigGroup" should be called with the name given to the
BeginConfigGroup. It is only possible to remove a config group that is not currently in use. Possible causes that
prevents the removal of a group may be:

 - Another registered a function outside the group uses a type from the group
 - A script is currently built that uses a type or function from the group
 - An instance of a script object that uses a type or function from the group is alive

It can be difficult to determine exactly where the use comes from so here's a few steps to do when RemoveConfigGroup
returns \ref asCONFIG_GROUP_IS_IN_USE.

 - Run a full cycle on the \ref doc_gc "garbage collector" to destroy lingering objects
 - \ref asIScriptEngine::DiscardModule "Discard" any module that may have been compiled with the group
 - Double check that no other group uses the entities from the group

*/