code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Template types</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Template types

A template type in AngelScript works similarly to how templates work in C++. The scripts will be able to instantiate different forms of the template type by specifying which subtype that should be used. The methods for the instance will then be adapted to this subtype, so that the correct handling of parameters and return types will be applied.

The implementation of the template type is not a C++ template though, instead it must be implemented as a generic class that can determine what to do dynamically at runtime based on the subtype for which it was instantiated. This is obviously a lot less efficient than having specific implementations for each type, and for that reason AngelScript permits the application to register a template specialization where the extra performance is needed.

This gives the best of both worlds, performance where the subtype is known before hand, and support for all other types that cannot be pre-determined.

Registering the template type

Template types can be either reference types or value types. Both are registered in a similar manner with only a few differences.

The name of the type is formed by the name of the template type plus the name of the subtype with angle brackets. Multiple subtypes can be informed, separated by comma. The type flag asOBJ_TEMPLATE must used to tell AngelScript that it is a template type that is being registered.

// Register the template type as a garbage collected reference type

r = engine->RegisterObjectType("myTemplate<class T>", 0, asOBJ_REF | asOBJ_GC | asOBJ_TEMPLATE); assert( r >= 0 );

// Register another template type as a value type

r = engine->RegisterObjectType("myValueTemplate<class T>", sizeof(MyValueTempl), asOBJ_VALUE | asOBJ_TEMPLATE | asGetTypeTraits<MyValueTempl>()); assert( r >= 0 );

asOBJ_REF

@ asOBJ_REF

A reference type.

Definition: angelscript.h:254

asOBJ_VALUE

@ asOBJ_VALUE

A value type.

Definition: angelscript.h:256

asOBJ_GC

@ asOBJ_GC

A garbage collected type. Only valid for reference types.

Definition: angelscript.h:258

asOBJ_TEMPLATE

@ asOBJ_TEMPLATE

A template type.

Definition: angelscript.h:266

The template type doesn't have to be garbage collected, but since you may not know which subtypes it will be instantiated for, it is usually best to implement that support.

When registering the behaviours, methods, and properties for the template type the type is identified with the name and subtype within angle brackets, but without the class token, e.g. myTemplate<T>. The sub type is identified by just the name of the subtype as it was declared in the call to RegisterObjectType.

The factory/construct behaviour for the template type is also different. In order for the implementation to know which subtype it is instantiated for, the factory/constructor receives the asITypeInfo of the template instance as a hidden first parameter. When registering the factory/constructor this hidden parameter is reflected in the declaration, for example as int &in.

// Register the factory behaviour

r = engine->RegisterObjectBehaviour("myTemplate<T>", asBEHAVE_FACTORY, "myTemplate<T>@ f(int&in)", asFUNCTIONPR(myTemplateFactory, (asITypeInfo*), myTemplate*), asCALL_CDECL); assert( r >= 0 );

// Register the construct behaviour

r = engine->RegisterObjectBehaviour("myValueTemplate<T>", asBEHAVE_CONSTRUCT, "void f(int&in)", asFUNCTIONPR(myValueTemplConstructor, (asITypeInfo*, void*), void), asCALL_CDECL_OBJLAST); assert( r >= 0 );

asFUNCTIONPR

#define asFUNCTIONPR(f, p, r)

Returns an asSFuncPtr representing the function specified by the name, parameter list,...

Definition: angelscript.h:694

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asCALL_CDECL_OBJLAST

@ asCALL_CDECL_OBJLAST

A cdecl function that takes the object pointer as the last parameter.

Definition: angelscript.h:238

asBEHAVE_FACTORY

@ asBEHAVE_FACTORY

Factory.

Definition: angelscript.h:366

asBEHAVE_CONSTRUCT

@ asBEHAVE_CONSTRUCT

Constructor.

Definition: angelscript.h:358

asITypeInfo

The interface for describing types This interface is used to describe the types in the script engine.

Definition: angelscript.h:3704

The list factory/constructor, used to instantiate objects with initialization lists, is registered in the same way, i.e.:

// Register the list factory behaviour

r = engine->RegisterObjectBehaviour("myTemplate<T>", asBEHAVE_LIST_FACTORY, "myTemplate<T>@ f(int&in, uint)", asFUNCTIONPR(myTemplateListFactory, (asITypeInfo*, unsigned int), myTemplate*), asCALL_CDECL); assert( r >= 0 );

// Register the list constructor behaviour

r = engine->RegisterObjectBehaviour("myValueTemplate<T>", asBEHAVE_LIST_CONSTRUCT, "void f(int&in, uint)", asFUNCTIONPR(myValueTemplListConstruct, (asITypeInfo*, unsigned int, void*), void), asCALL_CDECL_OBJLAST); assert( r >= 0 );

asBEHAVE_LIST_CONSTRUCT

@ asBEHAVE_LIST_CONSTRUCT

Constructor used exclusively for initialization lists.

Definition: angelscript.h:360

asBEHAVE_LIST_FACTORY

@ asBEHAVE_LIST_FACTORY

Factory used exclusively for initialization lists.

Definition: angelscript.h:368

Remember that since the subtype must be determined dynamically at runtime, it is not possible to declare functions to receive the subtype by value, nor to return it by value. Instead you'll have to design the methods and behaviours to take the type by reference. It is possible to use object handles, but then the script engine won't be able to instantiate the template type for primitives and other values types.

The same goes for object properties. Templates can have properties just like any other class, but the properties must not be of the template subtype, since it is not known at the time of registration the size of this type.

See also

array template object

On subtype replacement for template instances

When a template type is instanced in a declaration, e.g. a variable, the compiler enumerates all the members of the template type to verify if any subtype is used which requires replacement. In most cases the replacement is a direct one-to-one mapping, but in cases where the subtype is used as a const parameter reference, then an additional instruction may be needed to get the expected behaviour.

The following shows a method registered to take the subtype T as a const ref.

r = engine->RegisterObjectMethod("array<T>", "int find(const T&in value) const", ...);

If this template is instantiated with a handle as a subtype, e.g. array<Obj@>, then the method will become:

  int find(Obj @const &in value) const

This means that that the parameter takes the handle to a non-read only Obj. The actual handle cannot be modified, but the object the handle refers to can still be modified by the method. This in turn makes it impossible for a script to call the method if the handle the script has is read only.

To allow the application developer to say that the method should allow handles to read only objects, a special keyword if_handle_then_const should be used.

r = engine->RegisterObjectMethod("array<T>", "int find(const T&in if_handle_then_const value) const", ...);

Now this becomes:

  int find(const Obj @const &in value) const

This means that the parameter takes a const handle to a read only Obj, i.e. both the handle itself and the object instance it refers to cannot be modified by the method. Now the script will be able to call the method both with read only handles and non-read only handles.

Validating template instantiations at compile time

In order to avoid unnecessary runtime validations of invalid template instantiations, the application should preferably register the asBEHAVE_TEMPLATE_CALLBACK behaviour. This is a special behaviour function that the script engine will invoke every time a new template instance type is generated. The callback function can then perform necessary validations to verify if the type can be handled, and if not tell the engine that the instance isn't supported.

The callback function must be a global function that receives an asITypeInfo pointer, and should return a boolean. If the template instance is valid the return value should be true.

The function should also take a second parameter with an output reference to a boolean. This parameter should be set to true by the function if the template instance should not be garbage collected, which will make AngelScript clear the asOBJ_GC flag for the object type. If the template instance cannot form any circular references, then it doesn't need to be garbage collected, which reduces the work that has to be done by the garbage collector.

// Register the template callback

// Observe that the asITypeInfo pointer argument is represented by the int reference

r = engine->RegisterObjectBehaviour("myTemplate<T>", asBEHAVE_TEMPLATE_CALLBACK, "bool f(int &in, bool&out)", asFUNCTION(myTemplateCallback), asCALL_CDECL); assert( r >= 0 );

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

asBEHAVE_TEMPLATE_CALLBACK

@ asBEHAVE_TEMPLATE_CALLBACK

Callback for validating template instances.

Definition: angelscript.h:378

Here's an example callback function:

bool myTemplateCallback(asITypeInfo *ot, bool &dontGarbageCollect)

{

  // This template will only support primitive types

  int typeId = ot->GetSubTypeId();

  if( typeId & asTYPEID_MASK_OBJECT )

  {

    // The script is attempting to instantiate the

    // template with an object type, this is not allowed.

    return false;

  }

  // Tell AngelScript that this instance doesn't require garbage collection

  dontGarbageCollect = true;

  // Primitive types are allowed

  return true;

}

asTYPEID_MASK_OBJECT

@ asTYPEID_MASK_OBJECT

If any of these bits are set, then the type is an object.

Definition: angelscript.h:498

asITypeInfo::GetSubTypeId

virtual int GetSubTypeId(asUINT subTypeIndex=0) const =0

Returns the type id of the template sub type.

Template specializations

When registering a template specialization you override the template instance that AngelScript would normally do when compiling a declaration with the template type. This allow the application to register a completely different object with its own implementation for template specializations. Obviously it is recommended that the template specialization is registered so that to the script writer it is transparent, i.e. try to avoid having different method names or behaviours for the template type and template specializations.

With the exception of the type name, a template specialization is registered exactly like a normal type. The template specialization must be registered in the same namespace as the template itself.

// Register a template specialization for the float subtype

r = engine->RegisterObjectType("myTemplate<float>", 0, asOBJ_REF); assert( r >= 0 );

// Register the factory (there are no hidden parameters for specializations)

r = engine->RegisterObjectBehaviour("myTemplate<float>", asBEHAVE_FACTORY, "myTemplate<float>@ f()", asFUNCTIONPR(myTemplateFloatFactory, (), myTemplateFloat*), asCALL_CDECL); assert( r >= 0 );

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Timeout long running scripts</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Timeout long running scripts

To prevent long running scripts to freeze the application it may be necessary to add a way to timeout the execution. This article presents two different ways to do so.

With the line callback

The line callback feature can be used to perform some special treatment during execution of the scripts. The callback is called for every script statement, which makes it possible to verify if the script has

 executed for too long time and if so suspend the execution to be resumed at a later time.

Before calling the context's Execute method, set the callback function like so:

int ExecuteScriptWithTimeOut(asIScriptContext *ctx)

{

  // Define the timeout as 1 second

  DWORD timeOut = timeGetTime() + 1000;

  // Set up the line callback that will timout the script

  ctx->SetLineCallback(asFUNCTION(LineCallback), &timeOut, asCALL_CDECL);

  // Execute the script

  int status = ctx->Execute();

  // If the status is asEXECUTION_SUSPENDED the script can

  // be resumed by calling this function again.

  return status;

}

// The line callback function is called by the VM for each statement that is executed

void LineCallback(asIScriptContext *ctx, DWORD *timeOut)

{

  // If the time out is reached we suspend the script

  if( *timeOut < timeGetTime() )

    ctx->Suspend();

}

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

asIScriptContext

The interface to the virtual machine.

Definition: angelscript.h:2735

asIScriptContext::Execute

virtual int Execute()=0

Executes the prepared function.

asIScriptContext::Suspend

virtual int Suspend()=0

Suspends the execution, which can then be resumed by calling Execute again.

asIScriptContext::SetLineCallback

virtual int SetLineCallback(asSFuncPtr callback, void *obj, int callConv)=0

Sets a line callback function. The function will be called for each executed script statement.

Take a look at the sample Events to see this working.

Observe that if the script is compiled with asEP_BUILD_WITHOUT_LINE_CUES, the line callback will be invoked less frequently, though it is guaranteed to be invoked at least for every loop or function call.

With a secondary thread

A second thread can be set up to suspend the execution after the timeout. This thread can then be put to sleep so that it doesn't impact performance during the execution. When the thread wakes up it should call the context's Suspend method.

The below shows some possible code for doing this. Note that the code for setting up the thread is fictive, as this is different for each target OS.

// The variables that are shared between the threads

asIScriptContext *threadCtx;

int threadId;

// This function will be executed in the secondary thread

void SuspendThread()

{

  // Put the thread to sleep until the timeout (1 second)

  Sleep(1000);

  // When we wake-up we call the context's Suspend method

  ctx->Suspend();

}

// This function sets up the timeout thread and executes the script

int ExecuteScriptWithTimeOut(asIScriptContext *ctx)

{

  // Set the shared context pointer before creating the thread

  threadCtx = ctx;

  // Create the thread that will immediately go to sleep

  threadId = CreateThread(SuspendThread);

  // Execute the script

  int status = ctx->Execute();

  // Destroy the secondary thread before releasing the context

  DestroyThread(threadId);

  // Clear the global variables

  threadId = 0;

  threadCtx = 0;

  // If the status is asEXECUTION_SUSPENDED the script can

  // be resumed by calling this function again.

  return status;

}

Observe that this way of doing it is safe even if the AngelScript library has been built without multithread support.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6

repo_name: Antidote/openrpgeditor

license: mit


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: The variable parameter type</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

The variable parameter type

The application can register functions that take a reference to a variable type, which means that the function can receive a reference to a variable of any type. This is useful when making generic containers.

When a function is registered with this special parameter type, the function will receive both the reference and an extra argument with the type id of the variable type. The reference refers to the actual value that the caller sent, i.e. if the expression is an object handle then the reference will refer to the handle, not the actual object.

// An example usage with a native function

engine->RegisterGlobalFunction("void func_c(?&in)", asFUNCTION(func_c), asCALL_CDECL);

void func_c(void *ref, int typeId)

{

    // Do something with the reference

    // The type of the reference is determined through the type id

}

// An example usage with a generic function

engine->RegisterGlobalFunction("void func_g(?&in)", asFUNCTION(func_g), asCALL_GENERIC);

void func_g(asIScriptGeneric *gen)

{

    void *ref = gen->GetArgAddress(0);

    int typeId = gen->GetArgTypeId(0);

    func_c(ref, typeId);

}

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asCALL_GENERIC

@ asCALL_GENERIC

A function using the generic calling convention.

Definition: angelscript.h:242

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

asIScriptGeneric

The interface for the generic calling convention.

Definition: angelscript.h:3419

asIScriptGeneric::GetArgTypeId

virtual int GetArgTypeId(asUINT arg, asDWORD *flags=0) const =0

Returns the type id of the argument.

asIScriptGeneric::GetArgAddress

virtual void * GetArgAddress(asUINT arg)=0

Returns the address held in a reference or handle argument.

The variable type can also be used with out references, but not with inout references. Currently it can only be used with global functions, object constructors, and object methods. It cannot be used with other behaviours and operators.

The variable type is not available within scripts, so it can only be used to register application functions.

See also

any object and dictionary object for examples

Variable conversion operators

The variable parameter type can also be used in special versions of the opConv and opCast operator overloads. This is especially useful for generic container types that need to be able to hold any type of content.

void opCast(?&out)

void opConv(?&out)

See also

ref object and dictionary object for examples

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Weak references</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Weak references

Even though AngelScript uses a garbage collector to resolve cyclic references weak references may still come in handy. Weak references are especifically useful in scenarios were an object wants to be able to access other objects, but do not want to kept them alive longer than necessary.

AngelScript supports weak references with the use of shared booleans. The code that wants to keep a weak reference to an object should obtain the weakref flag from that object, which is a shared boolean, and before using the pointer to the object it should check if this flag has been set to indicate that the object is no longer alive.

Script classes automatically supports weak references without the script writing having to do anything. Application registered types on the other hand must register the behaviour asBEHAVE_GET_WEAKREF_FLAG and implement the logic to set the flag upon destroying the object.

The following code shows how to do a thread safe implementation:

class MyClass

{

public:

  MyClass() { refCount = 1; weakRefFlag = 0; }

  void AddRef() { asAtomicInc(refCount); }

  void Release()

  {

    // If the weak ref flag exists it is because someone held a weak ref

    // and that someone may add a reference to the object at any time. It

    // is ok to check the existance of the weakRefFlag without locking here

    // because if the refCount is 1 then no other thread is currently

    // creating the weakRefFlag.

    if( refCount == 1 && weakRefFlag )

    {

      // Set the flag to tell others that the object is no longer alive

      // We must do this before decreasing the refCount to 0 so we don't

      // end up with a race condition between this thread attempting to

      // destroy the object and the other that temporary added a strong

      // ref from the weak ref.

      weakRefFlag->Set(true);

    }

    if( asAtomicDec(refCount) == 0 )

      delete this;

  }

  asILockableSharedBool *GetWeakRefFlag()

  {

    if( !weakRefFlag )

    {

      // Lock globally so no other thread can attempt

      // to create a shared bool at the same time

      asAcquireExclusiveLock();

      // Make sure another thread didn't create the

      // flag while we waited for the lock

      if( !weakRefFlag )

        weakRefFlag = asCreateLockableSharedBool();

      asReleaseExclusiveLock();

    }

    return weakRefFlag;

  }

  static MyClass *Factory() { return new MyClass(); }

protected:

  ~MyClass()

  {

    // Release the weak reference flag that may still

    // be accessed by the code that holds a weak reference

    if( weakRefFlag )

      weakRefFlag->Release();

  }

  int refCount;

  asILockableSharedBool *weakRefFlag;

};

asILockableSharedBool

A lockable shared boolean.

Definition: angelscript.h:4257

asAcquireExclusiveLock

AS_API void asAcquireExclusiveLock()

Acquire an exclusive lock.

asAtomicDec

AS_API int asAtomicDec(int &value)

Decrements the value by one and returns the result as a single atomic instruction.

asReleaseExclusiveLock

AS_API void asReleaseExclusiveLock()

Release an exclusive lock.

asAtomicInc

AS_API int asAtomicInc(int &value)

Increments the value by one and returns the result as a single atomic instruction.

asCreateLockableSharedBool

AS_API asILockableSharedBool * asCreateLockableSharedBool()

Create a lockable shared boolean.

The asBEHAVE_GET_WEAKREF_FLAG behaviour for this class is registered like this:

engine->RegisterObjectType("MyClass", 0, asOBJ_REF);

engine->RegisterObjectBehaviour("MyClass", asBEHAVE_ADDREF, "void f()", asMETHOD(MyClass, AddRef), asCALL_THISCALL);

engine->RegisterObjectBehaviour("MyClass", asBEHAVE_RELEASE, "void f()", asMETHOD(MyClass, Release), asCALL_THISCALL);

engine->RegisterObjectBehaviour("MyClass", asBEHAVE_GET_WEAKREF_FLAG, "int &f()", asMETHOD(MyClass, GetWeakRefFlag), asCALL_THISCALL);

asCALL_THISCALL

@ asCALL_THISCALL

A thiscall class method.

Definition: angelscript.h:236

asMETHOD

#define asMETHOD(c, m)

Returns an asSFuncPtr representing the class method specified by class and method name.

Definition: angelscript.h:750

asBEHAVE_ADDREF

@ asBEHAVE_ADDREF

AddRef.

Definition: angelscript.h:370

asBEHAVE_RELEASE

@ asBEHAVE_RELEASE

Release.

Definition: angelscript.h:372

asBEHAVE_GET_WEAKREF_FLAG

@ asBEHAVE_GET_WEAKREF_FLAG

Obtain weak ref flag.

Definition: angelscript.h:374

asOBJ_REF

@ asOBJ_REF

A reference type.

Definition: angelscript.h:254

The script language doesn't have a built-in syntax for weak references. Instead a standard weakref add-on has been implemented to provide this for the applications that wants to provide this support in the scripts.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Advanced topics</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Advanced topics

Debugging scripts

Timeout long running scripts

Garbage collection

Multithreading

Concurrent scripts

Co-routines

Import functions

Dynamic compilations

Pre-compiled byte code

Fine tuning

Access masks and exposing different interfaces

Using namespaces

Dynamic configurations

Custom options

Reflection

Serialization

Inheriting from application registered class

JIT compilation

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
var doc_advanced =
[
    [ "Debugging scripts", "doc_debug.html", [
      [ "Setting line breaks", "doc_debug.html#doc_debug_1", null ],
      [ "Viewing the call stack", "doc_debug.html#doc_debug_2", null ],
      [ "Inspecting variables", "doc_debug.html#doc_debug_3", null ],
      [ "Debugging internally executed scripts", "doc_debug.html#doc_debug_4", null ]
    ] ],
    [ "Timeout long running scripts", "doc_adv_timeout.html", [
      [ "With the line callback", "doc_adv_timeout.html#doc_adv_timeout_1", null ],
      [ "With a secondary thread", "doc_adv_timeout.html#doc_adv_timeout_2", null ]
    ] ],
    [ "Garbage collection", "doc_gc.html", [
      [ "Callback for detected circular references", "doc_gc.html#doc_gc_circcallback", null ],
      [ "Garbage collection and multi-threading", "doc_gc.html#doc_gc_threads", null ]
    ] ],
    [ "Multithreading", "doc_adv_multithread.html", [
      [ "Things to think about with a multithreaded environment", "doc_adv_multithread.html#doc_adv_multithread_1", null ],
      [ "Fibers", "doc_adv_multithread.html#doc_adv_fibers", null ]
    ] ],
    [ "Concurrent scripts", "doc_adv_concurrent.html", null ],
    [ "Co-routines", "doc_adv_coroutine.html", null ],
    [ "Import functions", "doc_adv_import.html", null ],
    [ "Dynamic compilations", "doc_adv_dynamic_build.html", [
      [ "On demand builds", "doc_adv_dynamic_build.html#doc_adv_dynamic_build_ondemand", null ],
      [ "Incremental builds", "doc_adv_dynamic_build.html#doc_adv_dynamic_build_incr", null ],
      [ "Hot reloading scripts", "doc_adv_dynamic_build.html#doc_adv_dynamic_build_hot", [
        [ "Things to consider", "doc_adv_dynamic_build.html#doc_adv_dynamic_build_hot_1", null ]
      ] ]
    ] ],
    [ "Pre-compiled byte code", "doc_adv_precompile.html", [
      [ "Things to remember", "doc_adv_precompile.html#doc_adv_precompile_1", null ]
    ] ],
    [ "Fine tuning", "doc_finetuning.html", [
      [ "Cache the functions and types", "doc_finetuning.html#doc_finetuning_1", null ],
      [ "Reuse the context object", "doc_finetuning.html#doc_finetuning_2", [
        [ "Context pool", "doc_finetuning.html#doc_finetuning_2_1", null ],
        [ "Nested calls", "doc_finetuning.html#doc_finetuning_2_2", null ]
      ] ],
      [ "Compile scripts without line cues", "doc_finetuning.html#doc_finetuning_3", null ],
      [ "Disable thread safety", "doc_finetuning.html#doc_finetuning_4", null ],
      [ "Turn off automatic garbage collection", "doc_finetuning.html#doc_finetuning_5", null ],
      [ "Compare native calling convention versus generic calling convention", "doc_finetuning.html#doc_finetuning_6", null ]
    ] ],
    [ "Access masks and exposing different interfaces", "doc_adv_access_mask.html", null ],
    [ "Using namespaces", "doc_adv_namespace.html", [
      [ "Registering the interface with namespaces", "doc_adv_namespace.html#doc_adv_namespace_reg", null ],
      [ "Finding entities in namespaces", "doc_adv_namespace.html#doc_adv_namespace_enum", null ]
    ] ],
    [ "Dynamic configurations", "doc_adv_dynamic_config.html", null ],
    [ "Custom options", "doc_adv_custom_options.html", [
      [ "Registerable types", "doc_adv_custom_options.html#doc_adv_custom_options_reg_types", null ],
      [ "Language modifications", "doc_adv_custom_options.html#doc_adv_custom_options_lang_mod", null ],
      [ "Engine behaviours", "doc_adv_custom_options.html#doc_adv_custom_options_engine", null ]
    ] ],
    [ "Reflection", "doc_adv_reflection.html", [
      [ "Enumerating variables and properties", "doc_adv_reflection.html#doc_adv_reflection_vars", null ],
      [ "Enumerating functions and methods", "doc_adv_reflection.html#doc_adv_reflection_funcs", null ],
      [ "Enumerating types", "doc_adv_reflection.html#doc_adv_reflection_types", null ]
    ] ],
    [ "Serialization", "doc_serialization.html", [
      [ "Serialization of modules", "doc_serialization.html#doc_serialization_modules", null ],
      [ "Serialization of global variables", "doc_serialization.html#doc_serialization_vars", null ],
      [ "Serialization of objects", "doc_serialization.html#doc_serialization_objects", null ],
      [ "Serialization of contexts", "doc_serialization.html#doc_serialization_contexts", null ]
    ] ],
    [ "Inheriting from application registered class", "doc_adv_inheritappclass.html", null ],
    [ "JIT compilation", "doc_adv_jit_topic.html", "doc_adv_jit_topic" ]
];


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Advanced application interface</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Advanced application interface

Custom string type

Custom array type

Garbage collected objects

The generic calling convention

Registering a generic handle type

Registering a scoped reference type

Registering a single-reference type

Class hierarchies

The variable parameter type

Template types

Weak references

C++ exceptions and longjmp

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
var doc_advanced_api =
[
    [ "Custom string type", "doc_strings.html", [
      [ "Registering the custom string type", "doc_strings.html#doc_string_register", null ],
      [ "Unicode vs ASCII", "doc_strings.html#doc_strings_1", null ],
      [ "Multiline string literals", "doc_strings.html#doc_string_2", null ],
      [ "Character literals", "doc_strings.html#doc_string_3", null ]
    ] ],
    [ "Custom array type", "doc_arrays.html", null ],
    [ "Garbage collected objects", "doc_gc_object.html", [
      [ "GC support behaviours", "doc_gc_object.html#doc_reg_gcref_1", null ],
      [ "Factory for garbage collection", "doc_gc_object.html#doc_reg_gcref_2", null ],
      [ "Addref and release for garbage collection", "doc_gc_object.html#doc_reg_gcref_3", null ],
      [ "GC behaviours for value types", "doc_gc_object.html#doc_reg_gcref_value", null ],
      [ "Garbage collected objects and multi-threading", "doc_gc_object.html#doc_reg_gcref_4", null ]
    ] ],
    [ "The generic calling convention", "doc_generic.html", [
      [ "Extracting function arguments", "doc_generic.html#doc_generic_1", null ],
      [ "Returning values", "doc_generic.html#doc_generic_2", null ]
    ] ],
    [ "Registering a generic handle type", "doc_adv_generic_handle.html", null ],
    [ "Registering a scoped reference type", "doc_adv_scoped_type.html", null ],
    [ "Registering a single-reference type", "doc_adv_single_ref_type.html", null ],
    [ "Class hierarchies", "doc_adv_class_hierarchy.html", [
      [ "Establishing the relationship", "doc_adv_class_hierarchy.html#doc_adv_class_hierarchy_1", null ],
      [ "Inherited methods and properties", "doc_adv_class_hierarchy.html#doc_adv_class_hierarchy_2", null ]
    ] ],
    [ "The variable parameter type", "doc_adv_var_type.html", [
      [ "Variable conversion operators", "doc_adv_var_type.html#doc_adv_var_type_1", null ]
    ] ],
    [ "Template types", "doc_adv_template.html", [
      [ "Registering the template type", "doc_adv_template.html#doc_adv_template_1", [
        [ "On subtype replacement for template instances", "doc_adv_template.html#doc_adv_template_1_1", null ]
      ] ],
      [ "Validating template instantiations at compile time", "doc_adv_template.html#doc_adv_template_4", null ],
      [ "Template specializations", "doc_adv_template.html#doc_adv_template_2", null ]
    ] ],
    [ "Weak references", "doc_adv_weakref.html", null ],
    [ "C++ exceptions and longjmp", "doc_cpp_exceptions.html", [
      [ "Exceptions", "doc_cpp_exceptions.html#doc_cpp_exceptions_1", null ],
      [ "longjmp", "doc_cpp_exceptions.html#doc_cpp_exceptions_2", null ]
    ] ]
];


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Custom array type</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Custom array type

Like the string type, AngelScript doesn't have a built-in dynamic array type. Instead the application developers that wishes to allow dynamic arrays in the scripts should register this in the way that is best suited for the application. To save time a readily usable add-on is provided with a fully implemented dynamic array type.

If you wish to create your own array type, you'll need to understand how template types work. A template type is a special form of registering a type that the engine can then use to instanciate the true types based on the desired sub-types. This allow a single type registration to cover all possible array types that the script may need, instead of the application having to register a specific type for each type of array.

Of course, a generic type like this will have a drawback in performance due to runtime checks to determine the actual type, so the application should consider registering template specializations of the most common array types. This will allow the best optimizations for those types, and will also permit better interaction with the application as the template specialization can better match the actual array types that the application uses.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Datatypes in AngelScript and C++</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Datatypes in AngelScript and C++

Primitives

Primitives in AngelScript have direct matches in C++.

AngelScript	C++	Size (bits)

void 	void 	0

int8 	signed char 	8

int16 	signed short 	16

int 	signed int (*) 	32

int64 	signed int64_t 	64

uint8 	unsigned char 	8

uint16	unsigned short 	16

uint 	unsigned int (*) 	32

uint64	unsigned uint64_t 	64

float 	float 	32

double	double 	64

bool 	bool 	8 (**)

(*) An int can actually be of varying size on different platforms in C++, but most commonly it is 32 bits long. AngelScript will always assume 32 bits though.

(**) On 32 bit PowerPC platforms the bool type commonly have the size of 32 bit, when compiled on such platforms AngelScript also uses 32 bits for the bool type

Strings

AngelScript expects the application to register its own string type, so the string types should match perfectly.

The char* string type that is so convenient in C++ is however very difficult to use in a scripted environment where you do not have full control over how it is used. For that reason it is recommended that you wrap any functions that use the char* string type so that the string is properly converted to an object that can be safely handled by both the application and the script engine, e.g. std::string or another class of your preference.

Arrays

AngelScript also expects the application to register the type that should be used for dynamic arrays. Normally this is done by registering the array template object add-on, but the application is free to do it differently.

It is also possible to have different object types for different array types, so the application can match the array type exactly with the types used in C++.

Object handles

The AngelScript object handles are reference counted pointers to objects. This means that for object handles to work, the object must have some way of counting references, for example an AddRef/Release method pair.

When AngelScript passes an object handle by value to a function it increases the reference count to count for the argument instance, thus the function is responsible for releasing the reference once it is finished with it. In the same manner AngelScript expects any handle returned from a function to already have the reference accounted for.

However, when registering functions/methods with AngelScript the application can tell the library that it should automatically take care of releasing the handle references once a function return, likewise for returned handles. This is done by adding a + sign to the @ type modifier. When doing this an object handle can be safely passed to a C++ function that expects a normal pointer, but don't release it afterwards.

The syntax for using object handles in AngelScript is similar to C++ references, except the handles can be null and can be reassigned.

AngelScript handle	C++ pointer	C++ reference

obj @m_obj;	obj *m_obj = nullptr;	n/a

obj @m_obj = aReference;	obj *m_obj = aReference;	obj &m_obj = *aReference;

m_obj = aValue;	*m_obj = aValue;	m_obj = aValue;

@m_obj = aReference;	m_obj = aReference;	n/a

m_obj.callMe();	m_obj->callMe();	m_obj.callMe()

See also

Object handles to the application

Script classes and interfaces

All script classes and interfaces are seen as the asIScriptObject type by the application. The asIScriptObject interface has methods to determine the actual type of the script class or interface, as well as to interact with the actual object instance.

See also

Using script classes

Function pointers

All script function pointers are seen as the asIScriptFunction type by the application. The asIScriptFunction type has methods to obtain the name of the function and the parameter and return types, etc.

Parameter references

Because AngelScript needs to guarantee validity of pointers at all times, it doesn't always pass references to the true object to the function parameter. Instead it creates a copy of the object, whose reference is passed to the function, and if the reference is marked to return a value, the clone is copied back to the original object (if it still exists) once the function returns.

Because of this, AngelScript's parameter references are mostly compatible with C++ references, or pointers, except that the address normally shouldn't be stored for later use, since the object may be destroyed once the function returns.

If it is necessary to store the address of the object, then object handles should be used instead.

Reference	Description

&in	A copy of the value is always taken and the reference to the copy is passed to the function. For script functions this is not useful, but it is maintained for compatibility with application registered functions.

const &in	If the life time of the value can be guaranteed to be valid during the execution of the function, the reference to the true object is passed to the function, otherwise a copy is made.

&out	A reference to an unitialized value is passed to the function. When the function returns the value is copied to the true reference. The argument expression is evaluated only after the function call. This is the best way to have functions return multiple values.

const &out	Useless as the function wouldn't be able to modify the value.

&inout	The true reference is always passed to the function. Only objects that support object handles can be used with this type as they can always be guaranteed to stay alive during the call.

const &inout	The referred to object will be read-only.

If the application wants parameter references that work like they do in C++, then this can be allowed by setting an engine property.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Calling a script function</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Calling a script function

Preparing context and executing the function

Normally a script function is executed in a few steps:

Prepare the context

Set the function arguments

Execute the function

Retrieve the return value

The code for this might look something like this:

// Get a script context instance. Usually you'll want to reuse a previously

// created instance to avoid the overhead of allocating the instance with

// each call.

asIScriptContext *ctx = engine->CreateContext();

// Obtain the function from the module. This should preferrably

// be cached if the same function is called multiple times.

asIScriptFunction *func = engine->GetModule(module_name)->GetFunctionByDecl(function_declaration);

// Prepare() must be called to allow the context to prepare the stack

ctx->Prepare(func);

// Set the function arguments

ctx->SetArgDWord(...);

int r = ctx->Execute();

if( r == asEXECUTION_FINISHED )

{

  // The return value is only valid if the execution finished successfully

  asDWORD ret = ctx->GetReturnDWord();

}

// Release the context when you're done with it

ctx->Release();

asDWORD

unsigned long asDWORD

32 bit unsigned integer

Definition: angelscript.h:624

asEXECUTION_FINISHED

@ asEXECUTION_FINISHED

The context has successfully completed the execution.

Definition: angelscript.h:402

asIScriptContext

The interface to the virtual machine.

Definition: angelscript.h:2735

asIScriptContext::SetArgDWord

virtual int SetArgDWord(asUINT arg, asDWORD value)=0

Sets a 32-bit integer argument value.

asIScriptContext::Release

virtual int Release() const =0

Decrease reference counter.

asIScriptContext::Prepare

virtual int Prepare(asIScriptFunction *func)=0

Prepares the context for execution of the function.

asIScriptContext::GetReturnDWord

virtual asDWORD GetReturnDWord()=0

Returns the 32-bit return value.

asIScriptContext::Execute

virtual int Execute()=0

Executes the prepared function.

asIScriptFunction

The interface for a script function description.

Definition: angelscript.h:4000

asIScriptFunction::GetModule

virtual asIScriptModule * GetModule() const =0

Returns the module where the function is declared.

asIScriptModule::GetFunctionByDecl

virtual asIScriptFunction * GetFunctionByDecl(const char *decl) const =0

Returns the function by its declaration.

If your application allows the execution to be suspended, either by using the callback function or registering a function that allow the script to manually suspend the execution, then the execution function may return before finishing with the return code asEXECUTION_SUSPENDED. In that case you can later resume the execution by simply calling the execution function again.

Note that the return value retrieved with GetReturnValue() is only valid if the script function returned successfully, i.e. if Execute() returned asEXECUTION_FINISHED.

Passing and returning primitives

When calling script functions that take arguments, the values of these arguments must be set after the call to Prepare() and before Execute(). The arguments are set using a group of SetArg methods:

int SetArgDWord(int arg, asDWORD value);

int SetArgQWord(int arg, asQWORD value);

int SetArgFloat(int arg, float value);

int SetArgDouble(int arg, double value);

int SetArgByte(int arg, asBYTE value);

int SetArgWord(int arg, asWORD value);

asQWORD

unsigned __int64 asQWORD

64 bit unsigned integer

Definition: angelscript.h:629

asWORD

unsigned short asWORD

16 bit unsigned integer

Definition: angelscript.h:609

asBYTE

unsigned char asBYTE

8 bit unsigned integer

Definition: angelscript.h:608

arg is the argument number, where the first argument is on 0, the second on 1, and so on. value is the value of the argument. What method to use is determined by the type of the parameter. For primitive types you can use any of these. If the parameter type is a reference to a primitive type it is recommended to use the SetArgAddress() method and pass the pointer as the value. For non-primitive types the method SetArgObject() should be used, which will be described in the next section.

// The context has been prepared for a script

// function with the following signature:

// int function(int, double, bool, int &out)

// Put the arguments on the context stack, starting with the first one

ctx->SetArgDWord(0, 1);

ctx->SetArgDouble(1, 3.141592);

ctx->SetArgByte(2, true);

int val;

ctx->SetArgAddress(3, &val);

asIScriptContext::SetArgAddress

virtual int SetArgAddress(asUINT arg, void *addr)=0

Sets the address of a reference or handle argument.

asIScriptContext::SetArgByte

virtual int SetArgByte(asUINT arg, asBYTE value)=0

Sets an 8-bit argument value.

asIScriptContext::SetArgDouble

virtual int SetArgDouble(asUINT arg, double value)=0

Sets a double argument value.

Once the script function has been executed the return value is retrieved in a similar way using the group of GetReturn methods:

asDWORD GetReturnDWord();

asQWORD GetReturnQWord();

float   GetReturnFloat();

double  GetReturnDouble();

asBYTE  GetReturnByte();

asWORD  GetReturnWord();

Note that you must make sure the returned value is in fact valid, for example if the script function was interrupted by a script exception the value would not be valid. You do this by verifying the return code from Execute() or GetState(), where the return code should be asEXECUTION_FINISHED.

Passing and returning objects

Passing registered object types to a script function is done in a similar way to how primitive types are passed. The function to use is SetArgObject():

int SetArgObject(int arg, void *object);

arg is the argument number, just like the other SetArg methods. object is a pointer to the object you wish to pass.

This same method is used both for parameters passed by value and for those passed by reference. The library will automatically make a copy of the object if the parameter is defined to be passed by value.

// The complex object we wish to pass to the script function

CObject obj;

// Pass the object to the function

ctx->SetArgObject(0, &obj);

asIScriptContext::SetArgObject

virtual int SetArgObject(asUINT arg, void *obj)=0

Sets the object argument value.

Getting an object returned by a script function is done in a similar way, using GetReturnObject():

void *GetReturnObject();

This method will return a pointer to the object returned by the script function. The library will still hold a reference to the object, which will only be freed as the context is released.

// The object where we want to store the return value

CObject obj;

// Execute the function

int r = ctx->Execute();

if( r == asEXECUTION_FINISHED )

{

  // Get a pointer to the returned object and copy it to our object

  obj = *(CObject*)ctx->GetReturnObject();

}

asIScriptContext::GetReturnObject

virtual void * GetReturnObject()=0

Return a pointer to the returned object.

It is important to make a copy of the returned object, or if it is managed by reference counting add a reference to it. If this is not done the pointer obtained with GetReturnObject() will be invalidated as the context is released, or reused for another script function call.

Exception handling

If the script performs an illegal action, e.g. calling a method on a null handle, then the script engine will throw a script exception. The virtual machine will then abort the execution and the Execute method will return with the value asEXECUTION_EXCEPTION.

At this time it is possible to obtain information about the exception through the asIScriptContext's methods. Example:

void PrintExceptionInfo(asIScriptContext *ctx)

{

  asIScriptEngine *engine = ctx->GetEngine();

  // Determine the exception that occurred

  printf("desc: %s\n", ctx->GetExceptionString());

  // Determine the function where the exception occurred

  const asIScriptFunction *function = ctx->GetExceptionFunction();

  printf("func: %s\n", function->GetDeclaration());

  printf("modl: %s\n", function->GetModuleName());

  printf("sect: %s\n", function->GetScriptSectionName());

  // Determine the line number where the exception occurred

  printf("line: %d\n", ctx->GetExceptionLineNumber());

}

asIScriptContext::GetExceptionString

virtual const char * GetExceptionString()=0

Returns the exception string text.

asIScriptContext::GetExceptionLineNumber

virtual int GetExceptionLineNumber(int *column=0, const char **sectionName=0)=0

Returns the line number where the exception occurred.

asIScriptContext::GetEngine

virtual asIScriptEngine * GetEngine() const =0

Returns a pointer to the engine.

asIScriptContext::GetExceptionFunction

virtual asIScriptFunction * GetExceptionFunction()=0

Returns the function where the exception occurred.

asIScriptEngine

The engine interface.

Definition: angelscript.h:1102

asIScriptFunction::GetScriptSectionName

virtual const char * GetScriptSectionName() const =0

Returns the name of the script section where the function was implemented.

asIScriptFunction::GetModuleName

virtual const char * GetModuleName() const =0

Returns the name of the module where the function was implemented.

asIScriptFunction::GetDeclaration

virtual const char * GetDeclaration(bool includeObjectName=true, bool includeNamespace=false, bool includeParamNames=false) const =0

Returns the function declaration.

If desired, it is also possible to register a callback function that will be called at the moment the exception occurred, before the Execute method returns. The exception callback can then use WillExceptionBeCaught to determine if the exception will be caught within the script or if it will abort the execution.

See also

Debugging scripts for information on examining the callstack, and GetExceptionInfo for a helper function to get information on exceptions.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Funcdefs and script callback functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Funcdefs and script callback functions

Funcdefs are used to define a function signature for callbacks. This funcdef is then used to declare variables or function parameters that can hold handles to functions of matching signature.

The application can also register funcdefs as part of the application interface if the intention is for the script to set callbacks that will be called from the application. Once this is done, the application can receive the function handles as an asIScriptFunction pointer which can then be executed normally.

An example

Let's say the application needs to allow the script to set a callback that will then be called at some event. To do this the application would first register the funcdef that defines the signature of the callback. Then it needs to register the function that will be used to set the callback from the script.

// Register a simple funcdef for the callback

engine->RegisterFuncdef("void CallbackFunc()");

// Register a function for setting the callback

engine->RegisterGlobalFunction("void SetCallback(CallbackFunc @cb)", asFUNCTION(SetCallback), asCALL_CDECL);

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

With this interface, the script would be able to inform the callback like this:

  void main()
  {
    // Tell the application what script function to call
    SetCallback(MyCallback);
  }

  // The signature matches the registered CallbackFunc funcdef
  void MyCallback()
  {
    ...
  }

The implementation for the SetCallback function might look something like this.

// The callback is a script function.

// Don't forget to release this before cleaning up the engine.

asIScriptFunction *callback = 0;

void SetCallback(asIScriptFunction *cb)

{

  // Release the previous callback, if any

  if( callback )

    callback->Release();

  // Store the received handle for later use

  callback = cb;

  // Do not release the received script function

  // until it won't be used any more

}

asIScriptFunction

The interface for a script function description.

Definition: angelscript.h:4000

asIScriptFunction::Release

virtual int Release() const =0

Decrease reference counter.

To call the actual callback when it is time, the application uses the script context just like for any other call to a script function.

Delegates

Of course, callbacks can be used with delegates as well. Delegates are special function objects that holds a reference to an object and the method it should call on it. If this is exactly how the application should treat them, then the above example will work exactly the same and the application never needs to worry about whether the callback is actually a global function or a delegate object.

Sometimes however, it may be beneficial to break up the delegate, and have the application store the actual object and method separately, for example if the application should use a weak reference to avoid keeping the object alive longer than desired. The following shows how to retrieve the internals of the delegate:

// The callback, and accompanying object, if the callback is a class method

asIScriptFunction *callback           = 0;

void              *callbackObject     = 0;

asITypeInfo       *callbackObjectType = 0;

void SetCallback(asIScriptFunction *cb)

{

  // Release the previous callback, if any

  if( callback )

    callback->Release();

  if( callbackObject )

    engine->ReleaseScriptObject(callbackObject, callbackObjectType);

  callback           = 0;

  callbackObject     = 0;

  callbackObjectType = 0;

  if( cb && cb->GetFuncType() == asFUNC_DELEGATE )

  {

    callbackObject     = cb->GetDelegateObject();

    callbackObjectType = cb->GetDelegateObjectType();

    callback           = cb->GetDelegateFunction();

    // Hold on to the object and method

    engine->AddRefScriptObject(callbackObject, callbackObjectType);

    callback->AddRef();

    // Release the delegate, since it won't be used anymore

    cb->Release();

  }

  else

  {

    // Store the received handle for later use

    callback = cb;

    // Do not release the received script function

    // until it won't be used any more

  }

}

asFUNC_DELEGATE

@ asFUNC_DELEGATE

A function delegate.

Definition: angelscript.h:563

asIScriptFunction::AddRef

virtual int AddRef() const =0

Increases the reference counter.

asIScriptFunction::GetDelegateObject

virtual void * GetDelegateObject() const =0

Returns the object for the delegate.

asIScriptFunction::GetDelegateFunction

virtual asIScriptFunction * GetDelegateFunction() const =0

Returns the function for the delegate.

asIScriptFunction::GetFuncType

virtual asEFuncType GetFuncType() const =0

Returns the type of the function.

asIScriptFunction::GetDelegateObjectType

virtual asITypeInfo * GetDelegateObjectType() const =0

Returns the type of the delegated object.

asITypeInfo

The interface for describing types This interface is used to describe the types in the script engine.

Definition: angelscript.h:3704

Note

Although delegates use the asIScriptFunction interface, they are not actual functions. Because of this they are not owned by anymodule, i.e. GetModule will always return null. Likewise they do not have a specific function id, i.e. GetId will return 0.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Compile the library</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Compile the library

In the sdk/angelscript/projects directory you'll find project files for many of the popular compilers. However, these project files are not always up to date with the latest version of the library. If you get any compiler or linker errors please make sure the project file include all the files in the sdk/angelscript/source directory, and that the project settings are set according to this article.

If you don't find a project file for your compiler, you can easily create your own project by adding all the files in the sdk/angelscript/source directory, and configuring the project apropriately. If you have a new compiler/target that hasn't been used with AngelScript before, you may need to edit the as_config.h file to make sure the library is compiled properly.

See also

Considerations for specific platforms

Set compile time options

The code tries to contain compiler differences in as few places as possible. The header as_config.h was created for that purpose. There you will find some #defines that allow different compilers to work. You'll probably not have to change this file, but if you're using a compiler not previously used and you're getting compiler errors it might be worth it to take a look at this file.

There are also a couple of other #defines used in the code to alter the compilation. When compiling the library you might want to define ANGELSCRIPT_EXPORT so that library functions are exported. If you include the library source code directly in your application project you shouldn't have to define this flag.

If AS_DEPRECATED is defined then some backwards compatibility is maintained, this can help you do the upgrade to the latest version a little more smoothly. There is no guarantee that the backwards compatibility will be maintained though so try to remove use of deprecated functions as soon as possible.

Linking with the library

There are four ways of compiling and linking with AngelScript in order to use it. I recommend linking with a static library. Note that all four ways are interchangable with only a small change in your code, i.e a defined flag before including the header file, and possibly a routine for manually loading the dll. The rest of your code should look exactly the same for each of the alternatives.

1. Include library source files in project

You can take the source files for AngelScript and include them directly in your own project. The advantage of this is that you can be sure that the same compiler options are used for the library and the host applications, e.g. multi-threaded or single-threaded CRT. The disadvantage is that your project will be poluted with the library files.

The files that need to use the library should include the angelscript.h header with no need for any special settings.

// Include the library interface

#include "angelscript.h"

// ... Start using the library

angelscript.h

The API definition for AngelScript.

2. Compile a static library and link into project

The most recommended way is to compile a static library that your project will link with. When compiling the static library you have to make sure that the correct compiler settings are used so that you don't get conflicts in linkage with the CRT functions. This happens if you for example compile the library with dynamically linked multi-threaded CRT and your application with statically linked single-threaded CRT. (For Visual C++ you'll find these settings under Project -> Settings -> C/C++ -> Category: Code Generation)

To use the library you only need to include the angelscript.h header file.

// Include the library interface

#include "angelscript.h"

// ... Start using the library

3. Compile a dynamically loaded library with an import library

With Microsoft Visual C++ it is possible to compile a dynamically loaded library with an import library. The import library will then take care of the work needed to load the dll and bind the functions. A possible disadvantage of this method is that you are not able to give any user-friendly error messages in case loading the library fails.

To use the library you'll have to define ANGELSCRIPT_DLL_LIBRARY_IMPORT before including the angelscript.h header file.

// Include the library interface

#define ANGELSCRIPT_DLL_LIBRARY_IMPORT

#include "angelscript.h"

// ... Start using the library

4. Load the dynamically loaded library manually

If you want to use a dll, e.g. to share code between applications, I recommend loading the library manually as you can treat any failures to load or bind functions graciously.

To use manually loaded dll, you should define ANGELSCRIPT_DLL_MANUAL_IMPORT before including the angelscript.h header file. This will insure that the header file doesn't declare the function prototypes, as you will most likely want to use these names for the function pointers.

// Include the library interface

#define ANGELSCRIPT_DLL_MANUAL_IMPORT

#include "angelscript.h"

// Declare the function pointers

typedef asIScriptEngine * AS_CALL t_asCreateScriptEngine(int);

t_asCreateScriptEngine *asCreateScriptEngine = 0;

// ... Declare the rest of the functions

// Load the dll and bind the functions (error handling left out for clarity)

HMODULE dll = LoadLibrary("angelscript.dll");

asCreateScriptEngine = (t_asCreateScriptEngine*)GetProcAddress(dll, "_asCreateScriptEngine");

// ... Bind the other functions

// ... Start using the library

asIScriptEngine

The engine interface.

Definition: angelscript.h:1102

asCreateScriptEngine

AS_API asIScriptEngine * asCreateScriptEngine(asDWORD version=ANGELSCRIPT_VERSION)

Creates the script engine.

Considerations for specific platforms

As mentioned before, for most platforms the compilation of the library is as easy as including all source files and compiling them. However, on some platforms specific actions needs to be performed to compile the library correctly.

Windows 64bit

The MSVC compiler doesn't support inline assembler for the x86 64bit CPU family. To support this platform a separate assembler file has been created: as_callfunc_x64_msvc_asm.asm.

To compile this file it is necessary to configure a custom build command with the following:

ml64.exe /c  /nologo /Fo$(OutDir)\as_callfunc_x64_msvc_asm.obj /W3 /Zi /Ta $(InputDir)\$(InputFileName)

Microsoft Visual C++

While AngelScript doesn't use Microsoft's language extensions you may still face trouble compiling the library if you disable the language extensions. This is because Microsoft's own SDK may have code that relies on the language extensions, e.g. in version 6.0a you might get compiler errors due to the existance of $ in the macro definitions in the specstrings.h header from the Platform SDK. This particular problem was fixed by Microsoft in version 6.1 of their SDK, but there may be others so it might just easier to leave the language extensions turned on.

GNUC based compilers

In order to properly intergrate with C++ without the need for wrappers AngelScript uses a lot of pointer casts. Unfortunately it is not possible to always guarantee strict aliasing because of this, so on GNUC based compilers it is necessary to disable compiler optimizations that assume strict aliasing.

Use the following compiler argument to disable this:

-fno-strict-aliasing

Pocket PC with ARM CPU

The MSVC compiler doesn't support inline assembler for the ARM CPU, so a separate assembler file has been written with this code: as_callfunc_arm_msvc.asm.

In order to compile this file properly it is necessary to configure a custom build command with the following:

armasm -g $(InputPath)

Marmalade

Marmalade is a cross platform SDK created with mobile devices in mind. It functions by abstracting the underlying OS with its own C runtime library even though it uses the common C++ compilers, e.g. MSVC on Windows, and GNUC on Linux and Mac.

When compiling AngelScript with Marmalade for iOS and Android scons must be used in order to properly compile the native ARM assembler routines. For Windows Phone you should be able to use MSVC normally.

Size of the library

The size of the library depends on many different factors, such as compiler brand, compiler flags, and also what features of AngelScript that are included. However, to give an idea of how much space the library will take up on the disk and memory I've compiled the asrun sample in a few different ways and noted down the size.

Options	Size of binary on disk

32 bit / multithreaded dll / optimize for speed

Without including AngelScript	14KB

32 bit / multithreaded dll / optimize for speed

Using AngelScript and add-ons	796KB

32 bit / multithreaded dll / optimize for speed

AngelScript without compiler (AS_NO_COMPILER) and add-ons	453KB

32 bit / multithreaded static / optimize for speed

Using AngelScript but without add-ons	867KB

32 bit / multithreaded static / optimize for speed

Using AngelScript and add-ons	1015KB

64 bit / multithreaded static / optimize for speed

Using AngelScript and add-ons	1336KB

32 bit / multithreaded static / optimize for size

Using AngelScript and add-ons	797KB

32 bit / multithreaded dll / optimize for size

Using AngelScript and add-ons	582KB

Based on this we can draw the conclusion that the engine and VM takes up about 300KB when optimized for speed, the compiler adds another 350KB, and the add-ons yet another 150KB.

Note

These tests were made with MSVC 2012 and version 2.30.2 of the library.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Compiling scripts</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Compiling scripts

After registering the application interface it's time to compile the scripts that will be executed.

Message callback

Before starting the compilation, remember to have the message callback set in the engine so that you can get more information on compilation errors than just an error code. In fact, it is recommended to set the message callback right after creating the script engine, as the message callback may even be helpful while registering the application interface.

The message callback has been designed so that it doesn't output anything if there are no errors or warnings, so when everything is ok, you shouldn't get anything from it. But if the Build method returns an error, the message callback will have received detailed information about the error.

If desired, the application may send its own messages to the callback via the WriteMessage method on the engine.

// Implement a simple message callback function

void MessageCallback(const asSMessageInfo *msg, void *param)

{

  const char *type = "ERR ";

  if( msg->type == asMSGTYPE_WARNING )

    type = "WARN";

  else if( msg->type == asMSGTYPE_INFORMATION )

    type = "INFO";

  printf("%s (%d, %d) : %s : %s\n", msg->section, msg->row, msg->col, type, msg->message);

}

// Set the message callback when creating the engine

asIScriptEngine *engine = asCreateScriptEngine();

engine->SetMessageCallback(asFUNCTION(MessageCallback), 0, asCALL_CDECL);

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

asMSGTYPE_WARNING

@ asMSGTYPE_WARNING

The message is a warning.

Definition: angelscript.h:428

asMSGTYPE_INFORMATION

@ asMSGTYPE_INFORMATION

The message is informational only.

Definition: angelscript.h:430

asIScriptEngine

The engine interface.

Definition: angelscript.h:1102

asIScriptEngine::SetMessageCallback

virtual int SetMessageCallback(const asSFuncPtr &callback, void *obj, asDWORD callConv)=0

Sets a message callback that will receive compiler messages.

asCreateScriptEngine

AS_API asIScriptEngine * asCreateScriptEngine(asDWORD version=ANGELSCRIPT_VERSION)

Creates the script engine.

asSMessageInfo

Represents a compiler message.

Definition: angelscript.h:777

asSMessageInfo::col

int col

The column.

Definition: angelscript.h:783

asSMessageInfo::row

int row

The row number.

Definition: angelscript.h:781

asSMessageInfo::type

asEMsgType type

The type of message.

Definition: angelscript.h:785

asSMessageInfo::section

const char * section

The script section where the message is raised.

Definition: angelscript.h:779

asSMessageInfo::message

const char * message

The message text.

Definition: angelscript.h:787

Loading and compiling scripts

To build a script module you first obtain a module from the engine, then add the script sections, and finally compile them. A compiled script module may be composed of one or more script sections, so your application may store each section in different files, or even generate them dynamically. It doesn't matter in which order the script sections are added to the module, as the compiler is able to resolve all names regardless of where they are declared in the script.

// Create a new script module

asIScriptModule *mod = engine->GetModule("module", asGM_ALWAYS_CREATE);

// Load and add the script sections to the module

string script;

LoadScriptFile("script.as", script);

mod->AddScriptSection("script.as", script.c_str());

// Build the module

int r = mod->Build();

if( r < 0 )

{

  // The build failed. The message stream will have received

  // compiler errors that shows what needs to be fixed

}

asGM_ALWAYS_CREATE

@ asGM_ALWAYS_CREATE

Always create a new module, discarding the existing one.

Definition: angelscript.h:534

asIScriptEngine::GetModule

virtual asIScriptModule * GetModule(const char *module, asEGMFlags flag=asGM_ONLY_IF_EXISTS)=0

Return an interface pointer to the module.

asIScriptModule

The interface to the script modules.

Definition: angelscript.h:2232

asIScriptModule::AddScriptSection

virtual int AddScriptSection(const char *name, const char *code, size_t codeLength=0, int lineOffset=0)=0

Add a script section for the next build.

asIScriptModule::Build

virtual int Build()=0

Build the previously added script sections.

AngelScript doesn't provide built-in functions for loading script files as most applications have their own way of loading files. However, it is quite easy to write your own routines for loading script files, for example:

// Load the entire script file into a string buffer

void LoadScriptFile(const char *fileName, string &script)

{

  // Open the file in binary mode

  FILE *f = fopen("test.as", "rb");

  // Determine the size of the file

  fseek(f, 0, SEEK_END);

  int len = ftell(f);

  fseek(f, 0, SEEK_SET);

  // Load the entire file in one call

  script.resize(len);

  fread(&script[0], len, 1, f);

  fclose(f);

}

As AngelScript doesn't load the files itself, it also doesn't have built-in support for including other files from within the script. However, if you look in the add-on directory, you'll find a CScriptBuilder class that provides this support and more. It is a helper class for loading files, perform a pre-processing pass, and then building the module. You can a see an example of how to use the script builder in Your first script.

See also

Pre-compiled byte code

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: C++ exceptions and longjmp</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

C++ exceptions and longjmp

Exceptions

Application functions and class methods registered with the script engine are allowed to throw C++ exceptions. The virtual machine will automatically catch any C++ exception, abort the script execution, and return control to the application.

asIScriptContext *ctx = engine->CreateContext();

ctx->Prepare(engine->GetModule("test")->GetFunctionByName("func"));

int r = ctx->Execute();

if( r == asEXECUTION_EXCEPTION )

{

  string err = ctx->GetExceptionString();

  if( err == "Caught an exception from the application" )

  {

    // An application function threw an exception while being invoked from the script

    ...

  }

}

asEXECUTION_EXCEPTION

@ asEXECUTION_EXCEPTION

The execution was terminated by an unhandled script exception.

Definition: angelscript.h:408

asIScriptContext

The interface to the virtual machine.

Definition: angelscript.h:2735

asIScriptContext::GetExceptionString

virtual const char * GetExceptionString()=0

Returns the exception string text.

asIScriptContext::Prepare

virtual int Prepare(asIScriptFunction *func)=0

Prepares the context for execution of the function.

asIScriptContext::Execute

virtual int Execute()=0

Executes the prepared function.

By default the VM has no way of distinguishing between different types of exceptions and will just give a standard exception string for all of them. If desired a callback can be registered with the engine to provide a translation of the exception type to a more informative exception string.

void TranslateException(asIScriptContext *ctx, void* /*userParam*/)

{

  try

  {

    // Retrow the original exception so we can catch it again

    throw;

  }

  catch( std::exception &e )

  {

    // Tell the VM the type of exception that occurred

    ctx->SetException(e.what());

  }

  catch(...)

  {

    // The callback must not allow any exception to be thrown, but it is not necessary

    // to explicitly set an exception string if the default exception string is sufficient

  }

}

// Register the callback with the engine

engine->SetTranslateAppExceptionCallback(asFUNCTION(TranslateException), 0, asCALL_CDECL);

asCALL_CDECL

@ asCALL_CDECL

A cdecl function.

Definition: angelscript.h:230

asFUNCTION

#define asFUNCTION(f)

Returns an asSFuncPtr representing the function specified by the name.

Definition: angelscript.h:685

asIScriptContext::SetException

virtual int SetException(const char *info, bool allowCatch=true)=0

Sets an exception, which aborts the execution.

See also

GetExceptionInfo helper function

Note

The ability to catch exceptions can be turned off by compiling the library with the AS_NO_EXCEPTIONS defined. If this is done, the application should not register any functions that may throw exceptions, as the end result will be undefined should an exception occur.

longjmp

Some applications uses longjmp to do error handling. When performing a longjmp to a previously saved state, there is no chance for the code to do a cleanup of all that happened after the saved state. Because of that the application must not register functions that can perform a longjmp out from the function, as that can leave the virtual machine in an undefined state.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Data types</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Data types

Note that the host application may add types specific to that application, refer to the application's manual for more information.

Primitives

Objects and handles

Function handles

Strings

Auto declarations

See also

Standard library

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
var doc_datatypes =
[
    [ "Primitives", "doc_datatypes_primitives.html", [
      [ "void", "doc_datatypes_primitives.html#void", null ],
      [ "bool", "doc_datatypes_primitives.html#bool", null ],
      [ "Integer numbers", "doc_datatypes_primitives.html#int", null ],
      [ "Real numbers", "doc_datatypes_primitives.html#real", null ]
    ] ],
    [ "Objects and handles", "doc_datatypes_obj.html", [
      [ "Objects", "doc_datatypes_obj.html#objects", null ],
      [ "Object handles", "doc_datatypes_obj.html#handles", null ]
    ] ],
    [ "Function handles", "doc_datatypes_funcptr.html", [
      [ "Delegates", "doc_datatypes_funcptr.html#doc_datatypes_delegate", null ]
    ] ],
    [ "Strings", "doc_datatypes_strings.html", null ],
    [ "Auto declarations", "doc_datatypes_auto.html", null ]
];


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: array</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

array

Note

Arrays are only available in the scripts if the application registers the support for them. The syntax for using arrays may differ for the application you're working with so consult the application's manual for more details.

It is possible to declare array variables with the array identifier followed by the type of the elements within angle brackets.

Example:

  array<int> a, b, c;
  array<Foo@> d;

a, b, and c are now arrays of integers, and d is an array of handles to objects of the Foo type.

When declaring arrays it is possible to define the initial size of the array by passing the length as a parameter to the constructor. The elements can also be individually initialized by specifying an initialization list. Example:

  array<int> a;           // A zero-length array of integers
  array<int> b(3);        // An array of integers with 3 elements
  array<int> c(3, 1);     // An array of integers with 3 elements, all set to 1 by default
  array<int> d = {5,6,7}; // An array of integers with 3 elements with specific values

Multidimensional arrays are supported as arrays of arrays, for example:

  array<array<int>> a;                     // An empty array of arrays of integers
  array<array<int>> b = {{1,2},{3,4}}      // A 2 by 2 array with initialized values
  array<array<int>> c(10, array<int>(10)); // A 10 by 10 array of integers with uninitialized values

Each element in the array is accessed with the indexing operator. The indices are zero based, i.e. the range of valid indices are from 0 to length - 1.

  a[0] = some_value;

When the array stores handles the elements are assigned using the handle assignment.

  // Declare an array with initial length 1
  array<Foo@> arr(1);

  // Set the first element to point to a new instance of Foo
  @arr[0] = Foo();

Arrays can also be created and initialized within expressions as anonymous objects.

  // Call a function that expects an array of integers as input
  foo({1,2,3,4});

  // If the function has multiple overloads supporting different types with
  // initialization lists it is necessary to explicitly inform the array type
  foo2(array<int> = {1,2,3,4});

Supporting array object

The array object supports a number of operators and has several class methods to facilitate the manipulation of strings.

The array object is a reference type even if the elements are not, so it's possible to use handles to the array object when passing it around to avoid costly copies.

Operators

= assignment

The assignment operator performs a shallow copy of the content.

[] index operator

The index operator returns the reference of an element allowing it to be inspected or modified. If the index is out of range, then an exception will be raised.

==, != equality

Performs a value comparison on each of the elements in the two arrays and returns true if all match the used operator.

Methods

uint length() const

Returns the length of the array.

void resize(uint)

Sets the new length of the array.

void reverse()

Reverses the order of the elements in the array.

void insertAt(uint index, const T& in value)

 void insertAt(uint index, const array<T>& arr)

Inserts a new element, or another array of elements, into the array at the specified index.

void insertLast(const T& in)

Appends an element at the end of the array.

void removeAt(uint index)

Removes the element at the specified index.

void removeLast()

Removes the last element of the array.

void removeRange(uint start, uint count)

Removes count elements starting from start.

void sortAsc()

 void sortAsc(uint startAt, uint count)

Sorts the elements in the array in ascending order. For object types, this will use the type's opCmp method.

The second variant will sort only the elements starting at index startAt and the following count elements.

void sortDesc()

 void sortDesc(uint startAt, uint count)

These does the same thing as sortAsc except sorts the elements in descending order.

void sort(const less &in compareFunc, uint startAt = 0, uint count = uint(-1))

This method takes as input a callback function to use for comparing two elements when sorting the array.

The callback function should take as parameters two references of the same type of the array elements and it should return a bool. The return value should be true if the first argument should be placed before the second argument.

  array<int> arr = {3,2,1};
  arr.sort(function(a,b) { return a < b; });

The example shows how to use the sort method with a callback to an anonymous function.

Here's another example where the callback function is declared explicitly:

  bool lessForInt(const int &in a, const int &in b)
  {
    return a < b;
  }
  bool lessForHandle(const obj @&in a, const obj @&in b)
  {
    return a < b;
  }
  void sortArrayOfInts(array<int> @arr) { arr.sort(lessForInt); }
  void sortArrayOfHandles(array<obj@> @arr) { arr.sort(lessForHandle); }

int find(const T& in)

 int find(uint startAt, const T& in)

These will return the index of the first element that has the same value as the wanted value.

For object types, this will use the type's opEquals or opCmp method to compare the value. For arrays of handles any null handle will be skipped.

If no match is found the methods will return a negative value.

int findByRef(const T& in)

 int findByRef(uint startAt, const T& in)

These will search for a matching address. These are especially useful for arrays of handles where specific instances of objects are desired, and not just objects that happen to have equal value.

If no match is found the methods will return a negative value.

Script example

  int main()
  {
    array<int> arr = {1,2,3}; // 1,2,3
    arr.insertLast(0);        // 1,2,3,0
    arr.insertAt(2,4);        // 1,2,4,3,0
    arr.removeAt(1);          // 1,4,3,0

    arr.sortAsc();            // 0,1,3,4

    int sum = 0;
    for( uint n = 0; n < arr.length(); n++ )
      sum += arr[n];

    return sum;
  }

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6


code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>AngelScript: Auto declarations</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

AngelScript

          <input type="text" id="MSearchField" value="" placeholder="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Loading...

Searching...

No Matches

Auto declarations

It is possible to use 'auto' as the data type of an assignment-style variable declaration.

The appropriate type for the variable(s) will be automatically determined.

  auto i = 18;         // i will be an integer
  auto f = 18 + 5.f;   // the type of f resolves to float
  auto o = getLongObjectTypeNameById(id); // avoids redundancy for long type names

Auto can be qualified with const to force a constant value:

  const auto i = 2;  // i will be typed as 'const int'

For types that support handles, auto will always become a handle as it is more efficient than doing a value assignment. If the variable must not be a handle for some reason, then do not use the 'auto' keyword.

  auto  a = getObject();  // auto is typed 'obj@'
  auto@ b = getObject();  // this is still allowed if you want to be more explicit

Auto handles can not be used to declare class members, since their resolution is dependent on the constructor.

Generated on Sun May 21 2023 10:12:40 for AngelScript by  1.9.6