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: Script language grammar</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

Script language grammar

This is language grammar in Backus-Naur Form (BNF).

The following convention is used:

 ( )  - used for grouping
 { }  - 0 or more repetitions
 [ ]  - optional
  |   - or
 ' '  - token

SCRIPT        ::= {IMPORT | ENUM | TYPEDEF | CLASS | MIXIN | INTERFACE | FUNCDEF | VIRTPROP | VAR | FUNC | NAMESPACE | ';'}
NAMESPACE     ::= 'namespace' IDENTIFIER {'::' IDENTIFIER} '{' SCRIPT '}'
ENUM          ::= {'shared' | 'external'} 'enum' IDENTIFIER (';' | ('{' IDENTIFIER ['=' EXPR] {',' IDENTIFIER ['=' EXPR]} '}'))
CLASS         ::= {'shared' | 'abstract' | 'final' | 'external'} 'class' IDENTIFIER (';' | ([':' IDENTIFIER {',' IDENTIFIER}] '{' {VIRTPROP | FUNC | VAR | FUNCDEF} '}'))
TYPEDEF       ::= 'typedef' PRIMTYPE IDENTIFIER ';'
FUNC          ::= {'shared' | 'external'} ['private' | 'protected'] [((TYPE ['&']) | '~')] IDENTIFIER PARAMLIST ['const'] FUNCATTR (';' | STATBLOCK)
INTERFACE     ::= {'external' | 'shared'} 'interface' IDENTIFIER (';' | ([':' IDENTIFIER {',' IDENTIFIER}] '{' {VIRTPROP | INTFMTHD} '}'))
VAR           ::= ['private'|'protected'] TYPE IDENTIFIER [( '=' (INITLIST | EXPR)) | ARGLIST] {',' IDENTIFIER [( '=' (INITLIST | EXPR)) | ARGLIST]} ';'
IMPORT        ::= 'import' TYPE ['&'] IDENTIFIER PARAMLIST FUNCATTR 'from' STRING ';'
FUNCDEF       ::= {'external' | 'shared'} 'funcdef' TYPE ['&'] IDENTIFIER PARAMLIST ';'
VIRTPROP      ::= ['private' | 'protected'] TYPE ['&'] IDENTIFIER '{' {('get' | 'set') ['const'] FUNCATTR (STATBLOCK | ';')} '}'
MIXIN         ::= 'mixin' CLASS
INTFMTHD      ::= TYPE ['&'] IDENTIFIER PARAMLIST ['const'] ';'
STATBLOCK     ::= '{' {VAR | STATEMENT} '}'
PARAMLIST     ::= '(' ['void' | (TYPE TYPEMOD [IDENTIFIER] ['=' EXPR] {',' TYPE TYPEMOD [IDENTIFIER] ['=' EXPR]})] ')'
TYPEMOD       ::= ['&' ['in' | 'out' | 'inout']]
TYPE          ::= ['const'] SCOPE DATATYPE ['<' TYPE {',' TYPE} '>'] { ('[' ']') | ('@' ['const']) }
INITLIST      ::= '{' [ASSIGN | INITLIST] {',' [ASSIGN | INITLIST]} '}'
SCOPE         ::= ['::'] {IDENTIFIER '::'} [IDENTIFIER ['<' TYPE {',' TYPE} '>'] '::']
DATATYPE      ::= (IDENTIFIER | PRIMTYPE | '?' | 'auto')
PRIMTYPE      ::= 'void' | 'int' | 'int8' | 'int16' | 'int32' | 'int64' | 'uint' | 'uint8' | 'uint16' | 'uint32' | 'uint64' | 'float' | 'double' | 'bool'
FUNCATTR      ::= {'override' | 'final' | 'explicit' | 'property'}
STATEMENT     ::= (IF | FOR | WHILE | RETURN | STATBLOCK | BREAK | CONTINUE | DOWHILE | SWITCH | EXPRSTAT | TRY)
SWITCH        ::= 'switch' '(' ASSIGN ')' '{' {CASE} '}'
BREAK         ::= 'break' ';'
FOR           ::= 'for' '(' (VAR | EXPRSTAT) EXPRSTAT [ASSIGN {',' ASSIGN}] ')' STATEMENT
WHILE         ::= 'while' '(' ASSIGN ')' STATEMENT
DOWHILE       ::= 'do' STATEMENT 'while' '(' ASSIGN ')' ';'
IF            ::= 'if' '(' ASSIGN ')' STATEMENT ['else' STATEMENT]
CONTINUE      ::= 'continue' ';'
EXPRSTAT      ::= [ASSIGN] ';'
TRY           ::= 'try' STATBLOCK 'catch' STATBLOCK
RETURN        ::= 'return' [ASSIGN] ';'
CASE          ::= (('case' EXPR) | 'default') ':' {STATEMENT}
EXPR          ::= EXPRTERM {EXPROP EXPRTERM}
EXPRTERM      ::= ([TYPE '='] INITLIST) | ({EXPRPREOP} EXPRVALUE {EXPRPOSTOP})
EXPRVALUE     ::= 'void' | CONSTRUCTCALL | FUNCCALL | VARACCESS | CAST | LITERAL | '(' ASSIGN ')' | LAMBDA
CONSTRUCTCALL ::= TYPE ARGLIST
EXPRPREOP     ::= '-' | '+' | '!' | '++' | '--' | '~' | '@'
EXPRPOSTOP    ::= ('.' (FUNCCALL | IDENTIFIER)) | ('[' [IDENTIFIER ':'] ASSIGN {',' [IDENTIFIER ':' ASSIGN} ']') | ARGLIST | '++' | '--'
CAST          ::= 'cast' '<' TYPE '>' '(' ASSIGN ')'
LAMBDA        ::= 'function' '(' [[TYPE TYPEMOD] [IDENTIFIER] {',' [TYPE TYPEMOD] [IDENTIFIER]}] ')' STATBLOCK
LITERAL       ::= NUMBER | STRING | BITS | 'true' | 'false' | 'null'
FUNCCALL      ::= SCOPE IDENTIFIER ARGLIST
VARACCESS     ::= SCOPE IDENTIFIER
ARGLIST       ::= '(' [IDENTIFIER ':'] ASSIGN {',' [IDENTIFIER ':'] ASSIGN} ')'
ASSIGN        ::= CONDITION [ ASSIGNOP ASSIGN ]
CONDITION     ::= EXPR ['?' ASSIGN ':' ASSIGN]
EXPROP        ::= MATHOP | COMPOP | LOGICOP | BITOP
BITOP         ::= '&' | '|' | '^' | '<<' | '>>' | '>>>'
MATHOP        ::= '+' | '-' | '*' | '/' | '%' | '**'
COMPOP        ::= '==' | '!=' | '<' | '<=' | '>' | '>=' | 'is' | '!is'
LOGICOP       ::= '&&' | '||' | '^^' | 'and' | 'or' | 'xor'
ASSIGNOP      ::= '=' | '+=' | '-=' | '*=' | '/=' | '|=' | '&=' | '^=' | '%=' | '**=' | '<<=' | '>>=' | '>>>='
IDENTIFIER    ::= single token:  starts with letter or _, can include any letter and digit, same as in C++
NUMBER        ::= single token:  includes integers and real numbers, same as C++
STRING        ::= single token:  single quoted ', double quoted ", or heredoc multi-line string """
BITS          ::= single token:  binary 0b or 0B, octal 0o or 0O, decimal 0d or 0D, hexadecimal 0x or 0X
COMMENT       ::= single token:  starts with // and ends with new line or starts with /* and ends with */
WHITESPACE    ::= single token:  spaces, tab, carriage return, line feed, and UTF8 byte-order-mark

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: Script classes</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

Script classes

Script classes are declared globally and provides an easy way of grouping properties and methods into logical units. The syntax for classes is similar to C++ and Java.

Script class overview

Class constructors

Initialization of class members

Class destructor

Class methods

Inheritance and polymorphism

Protected and private class members

Operator overloads

Property accessors

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

repo_name: Antidote/openrpgeditor

license: mit


code:
var doc_script_class =
[
    [ "Script class overview", "doc_script_class_desc.html", null ],
    [ "Class constructors", "doc_script_class_construct.html", null ],
    [ "Initialization of class members", "doc_script_class_memberinit.html", null ],
    [ "Class destructor", "doc_script_class_destruct.html", null ],
    [ "Class methods", "doc_script_class_methods.html", [
      [ "Const methods", "doc_script_class_methods.html#doc_script_class_const", null ]
    ] ],
    [ "Inheritance and polymorphism", "doc_script_class_inheritance.html", [
      [ "Extra control with final, abstract, and override", "doc_script_class_inheritance.html#doc_script_class_inheritance_2", null ]
    ] ],
    [ "Protected and private class members", "doc_script_class_private.html", null ],
    [ "Operator overloads", "doc_script_class_ops.html", [
      [ "Prefixed unary operators", "doc_script_class_ops.html#doc_script_class_unary_ops", null ],
      [ "Postfixed unary operators", "doc_script_class_ops.html#doc_script_class_unary2_ops", null ],
      [ "Comparison operators", "doc_script_class_ops.html#doc_script_class_cmp_ops", null ],
      [ "Assignment operators", "doc_script_class_ops.html#doc_script_class_assign_ops", null ],
      [ "Binary operators", "doc_script_class_ops.html#doc_script_class_binary_ops", null ],
      [ "Index operators", "doc_script_class_ops.html#doc_script_class_index_op", null ],
      [ "Functor operator", "doc_script_class_ops.html#doc_script_class_call", null ],
      [ "Type conversion operators", "doc_script_class_ops.html#doc_script_class_conv", null ]
    ] ],
    [ "Property accessors", "doc_script_class_prop.html", [
      [ "Indexed property accessors", "doc_script_class_prop.html#doc_script_class_prop_index", 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: Class constructors</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

Class constructors

Class constructors are specific methods that will be used to create new instances of the class. It is not required for a class to declare constructors, but doing so may make it easier to use the class as it will not be necessary to first instantiate the class and then manually set the properties.

The constructors are declared without a return type, and must have the same name as the class itself. Multiple constructors with different parameter lists can be implemented for different forms of initializations.

  class MyClass
  {
    // Implement a default constructor
    MyClass()
    {
    }

    // Implement the copy constructor
    MyClass(const MyClass &in other)
    {
      // Copy the value of the other instance
    }

    // Implement other constructors with different parameter lists
    MyClass(int a, string b) {}
    MyClass(float x, float y, float z) {}

    // Implement conversion constructors
    // The second can only be used explicitly
    MyClass(int a) {}
    MyClass(string a) explicit {}
  }

The copy constructor is a specific constructor that the compiler can use to build more performatic code when copies of an object must be made. Without the copy constructor the compiler will be forced to first instantiate the copy using the default constructor, and then copy the attributes with the opAssign method.

A constructor that takes a single argument can be used in type conversions. By default the compiler can use these to perform the conversion implicitly when necessary. If that is not desired, then it is possible to prohibit this by adding the explicit decorator after the constructor.

One constructor cannot call another constructor. If you wish to share implementations in the constructors you should use a specific method for that.

If a class isn't explicitly declared with any constructor, the compiler will automatically provide a default constructor for the class. This automatically generated constructor will simply call the default constructor for all object members, and set all handles to null. If a member cannot be initialized with a default constructor, then a compiler error will be emitted.

How the members shall be initialized can also be defined directly in the declaration of the members. When this is done the initialization expression will automatically be compiled in the constructor without the need to write the initialization again.

See also

Initialization of class members, Type conversion operators

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: Script class overview</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

Script class overview

With classes the script writer can declare new data types that hold groups of properties and methods to manipulate them.

Script classes are reference types, which means that multiple references or handles can be held for the same object instance. The classes uses automatic memory management so the object instances are only destroyed when the last reference to the instance is cleared.

  // The class declaration
  class MyClass
  {
    // A class method
    void DoSomething() {}

    // Class properties
    int a;
    int b;
  }

A class can implement specific methods to overload operators. This can simplify how the object instances are used in expressions, so that it is not necessary to explicitly name each function, e.g. the opAdd method translates to the + operator.

Another useful feature is the ability to implement property accessors, which can be used either to provide virtual properties, i.e. that look like properties but really aren't, or to implement specific routines that must be executed everytime a property is accessed.

A script class can also inherit from other classes, and implement interfaces.

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: Class destructor</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

Class destructor

It is normally not necessary to implement the class destructor as AngelScript will by default free up any resources the objects holds when it is destroyed. However, there may be situations where a more explicit cleanup routine must be done as part of the destruction of the object.

The destructor is declared similarly to the constructor, except that it must be prefixed with the ~ symbol (also known as the bitwise not operator).

  class MyClass
  {
    // Implement the destructor if explicit cleanup is needed
    ~MyClass()
    {
      // Perform explicit cleanup here
    }
  }

Observe that AngelScript uses automatic memory management with garbage collection so it may not always be easy to predict when the destructor is executed. AngelScript will also call the destructor only once, even if the object is resurrected by adding a reference to it while executing the destructor.

It is not possible to directly invoke the destructor. If you need to be able to directly invoke the cleanup, then you should implement a public method for that.

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: Inheritance and polymorphism</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

Inheritance and polymorphism

AngelScript supports single inheritance, where a derived class inherits the properties and methods of its base class. Multiple inheritance is not supported, but polymorphism is supported by implementing interfaces, and code reuse is provided by including mixin classes.

All the class methods are virtual, so it is not necessary to specify this manually. When a derived class overrides an implementation, it can extend the original implementation by specifically calling the base class' method using the scope resolution operator. When implementing the constructor for a derived class the constructor for the base class is called using the super keyword. If none of the base class' constructors is manually called, the compiler will automatically insert a call to the default constructor in the beginning. The base class' destructor will always be called after the derived class' destructor, so there is no need to manually do this.

  // A derived class
  class MyDerived : MyBase
  {
    // The default constructor
    MyDerived()
    {
      // Calling the non-default constructor of the base class
      super(10);

      b = 0;
    }

    // Overloading a virtual method
    void DoSomething()
    {
      // Call the base class' implementation
      MyBase::DoSomething();

      // Do something more
      b = a;
    }

    int b;
  }

A class that is derived from another can be implicitly cast to the base class. The same works for interfaces that are implemented by a class. The other direction requires an explicit cast, as it is not known at compile time if the cast is valid.

  class A {}
  class B : A {}
  void Foo()
  {
    A @handle_to_A;
    B @handle_to_B;

    @handle_to_A = A(); // OK
    @handle_to_A = B(); // OK. The reference will be implicitly cast to A@

    @handle_to_B = A(); // Not OK. This will give a compilation error
    @handle_to_B = B(); // OK

    @handle_to_A = handle_to_B; // OK. The reference will be implicitly cast to A@
    @handle_to_B = handle_to_A; // Not OK. This will give a compilation error

    @handle_to_B = cast<B>(handle_to_A); // OK. Though, the explicit cast will return null
                                         // if the object in handle_to_a is not really an
                                         // instance of B
  }

Extra control with final, abstract, and override

A class can be marked as 'final' to prevent the inheritance of it. This is an optional feature and mostly used in larger projects where there are many classes and it may be difficult to manually control the correct use of all classes. It is also possible to mark individual class methods of a class as 'final', in which case it is still possible to inherit from the class, but the finalled method cannot be overridden.

Another keyword that can be used to mark a class is 'abstract'. Abstract classes cannot be instantiated, but they can be derived from. Abstract classes are most frequently used when you want to create a family of classes by deriving from a common base class, but do not want the base class to be instantiated by itself. It is currently not possible to mark methods as abstract so all methods must have an implementation even for abstract classes.

  // A final class that cannot be inherited from
  final class MyFinal
  {
    MyFinal() {}
    void Method() {}
  }

  // A class with individual methods finalled
  class MyPartiallyFinal
  {
    // A final method that cannot be overridden
    void Method1() final {}

    // Normal method that can still be overridden by derived class
    void Method2() {}
  }

  // An abstract class
  abstract class MyAbstractBase {}

When deriving a class it is possible to tell the compiler that a method is meant to override a method in the inherited base class. When this is done and there is no matching method in the base class the compiler will emit an error, as it knows that something wasn't implemented quite the way it was meant. This is especially useful to catch errors in large projects where a base class might be modified, but the derived classes was forgotten.

  class MyBase
  {
    void Method() {}
    void Method(int) {}
  }

  class MyDerived : MyBase
  {
    void Method() override {}      // OK. The method is overriding a method in the base class
    void Method(float) override {} // Not OK. The method isn't overriding a method in base class
  }

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: Initialization of class members</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

Initialization of class members

The order in which the class members are initialized during the construction of an object becomes important when using inheritance, or when defining the initialization of the members directly in the declaration. If a member is accessed before it has been initialized the script may cause a null handle access exception, which will abort the execution of the script.

For a simple class, the order in which the members are initialized is the same as the order in which they were declared. When explicit initializations are given in the declaration of the members, these members will be initialized last.

  // The order of this class will be: a, c, b, d
  class Foo
  {
    string a;
    string b = a;
    string c;
    string d = b;
  }

When inheritance is used, the derived class' members without explicit initialization will be initialized before the base class' members, and the members with explicit initialization will be initialized after the base class' members.

  // The order of this class will be: a, b
  class Bar
  {
    string a;
    string b = a;
  }

  // The order of this class will be: d, a, b, c
  class Foo : Bar
  {
    string c = a;
    string d;
  }

This order of initialization has been chosen to avoid most problems with accessing members before they have been initialized.

All members are initialized immediately in the beginning of the defined constructor, so the rest of the code in the constructor can access members without worry. The exception is when the constructor explicitly initializes a base class by calling super(), in this case the members with explicit initialization will remain uninitialized until after the base class has been fully constructed.

  class Bar
  {
    Bar(string val) { a = val; }
    string a;
  }

  class Foo : Bar
  {
    Foo()
    {
      // b is already initialized here

      super(b); // a will be initialized in this call

      // c is initialized right after super() returns
    }

    string b;
    string c = a;
  }

Be wary about cases where a constructor or member initialization calls class methods. As class methods can be overridden by derived classes it is possible for a base class to unwittingly access a member of the derived class before it has been initialized.

  class Bar
  {
    Bar()
    {
      DoSomething();
    }

    void DoSomething() {}
  }

  // This class will cause a null handle exception, because the Bar's constructor calls
  // the DoSomething() method that accesses the member msg before it has been initialized.
  class Foo : Bar
  {
    string msg = 'hello';
    void DoSomething()
    {
      print(msg);
    }
  }

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: Class methods</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

Class methods

The class methods are implemented the same way as global functions, with the addition that the class method can access the class instance properties either directly or through the 'this' keyword in the case a local variable has the same name.

  // The class declaration
  class MyClass
  {
    // A class method
    void DoSomething()
    {
      // The class properties can be accessed directly
      a *= 2;

      // The declaration of a local variable may hide class properties
      int b = 42;

      // In this case the class property have to be accessed explicitly
      this.b = b;
    }

    // Class properties
    int a;
    int b;
  }

Const methods

Classes add a new type of function overload, i.e. const overload. When a class method is accessed through a read-only reference or handle, only methods that have been marked as constant can be invoked. When the reference or handle is writable, then both types can be invoked, with the preference being the non-const version in case both matches.

  class CMyClass
  {
    int method()       { a++; return a; }
    int method() const {      return a; }
    int a;
  }
  void Function()
  {
     CMyClass o;
     const CMyClass @h = o;

     o.method(); // invokes the non-const version that increments the member a
     h.method(); // invokes the const version that doesn't increment the member a
  }

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: Operator overloads</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

Operator overloads

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

This is called operator overloading, and is done by implementing specific class methods. The compiler will recognize and use these

 methods when it compiles expressions involving the overloaded operators and the script class.

Prefixed unary operators

op	opfunc

- 	opNeg

~ 	opCom

++ 	opPreInc

-- 	opPreDec

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

Postfixed unary operators

op	opfunc

++ 	opPostInc

-- 	opPostDec

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

Comparison operators

op	opfunc

== 	opEquals

!= 	opEquals

< 	opCmp

<= 	opCmp

> 	opCmp

>= 	opCmp

is 	opEquals

!is 	opEquals

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

The comparison operators are rewritten as a.opCmp(b) op 0 and 0 op b.opCmp(a) and then the best match is used. The opCmp method must be implemented to return a int in order to be considered by the compiler. If the method argument is to be considered larger than the object then the method should return a negative value. If they are supposed to be equal the return value should be 0.

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

The identity operator, is, expects opEquals to take a handle, @, so the addresses can be compared to be able to return if it is the same object, in contrast two different objects that have the same value.

Assignment operators

op	opfunc

= 	opAssign

+= 	opAddAssign

-= 	opSubAssign

*= 	opMulAssign

/= 	opDivAssign

%= 	opModAssign

**= 	opPowAssign

&= 	opAndAssign

|= 	opOrAssign

^= 	opXorAssign

<<= 	opShlAssign

>>= 	opShrAssign

>>>= 	opUShrAssign

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

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

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

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

Binary operators

op	opfunc	opfunc_r

+ 	opAdd 	opAdd_r

- 	opSub 	opSub_r

* 	opMul 	opMul_r

/ 	opDiv 	opDiv_r

% 	opMod 	opMod_r

** 	opPow 	opPow_r

& 	opAnd 	opAnd_r

| 	opOr 	opOr_r

^ 	opXor 	opXor_r

<< 	opShl 	opShl_r

>> 	opShr 	opShr_r

>>> 	opUShr 	opUShr_r

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

Index operators

op	opfunc

[] 	opIndex

When the expression a[i] is compiled, the compiler will rewrite it as a.opIndex(i) and compile that instead. Multiple arguments between the brackets is also supported.

The index operator can also be formed similarly to property accessors. The get accessor should then be named get_opIndex and have one parameter for the indexing. The set accessor should be named set_opIndex and have two parameters, the first is for the indexing, and the second for the new value.

  class MyObj
  {
    float get_opIndex(int idx) const       { return 0; }
    void set_opIndex(int idx, float value) { }
  }

When the expression a[i] is used to retrieve the value, the compiler will rewrite it as a.get_opIndex(i). When the expression is used to set the value, the compiler will rewrite it as a.set_opIndex(i, expr).

Functor operator

op	opfunc

() 	opCall

When the expression expr(arglist) is compiled and expr evaluates to an object, the compiler will rewrite it as expr.opCall(arglist) and compile that instead.

Type conversion operators

op	opfunc

type(expr)	constructor, opConv, opImplConv

cast<type>(expr)	opCast, opImplCast

When the expression type(expr) is compiled and type doesn't have a conversion constructor that take an argument with the type of the expression, the compiler will try to rewrite it as expr.opConv(). The compiler will then chose the opConv that returns the desired type.

For implicit conversions, the compiler will look for a conversion constructor of the target type that take a matching argument, and isn't flagged as explicit. If it doesn't find one, it will try to call the opImplConv on the source type that returns the target type.

  class MyObj
  {
    double myValue;

    // Allow MyObj to be implicitly created from double
    MyObj(double v)            { myValue = v; }

    // Allow MyObj to be implicitly converted to double
    double opImplConv() const  { return myValue; }

    // Allow MyObj to be created from int, but only explicitly
    MyObj(int v) explicit      { myValue = v; }

    // Allow MyObj to be converted to int, but only explicitly
    int opConv() const         { return int(myValue); }
  }

This should only be used for value conversions and not reference casts. That is, the methods are expected to return a new instance of the value with the new type.

Note

When compiling the boolean expressions in conditions the compiler will not use the bool opImplConv on reference types even if the class method is implemented. This is because it is ambigous if it is the handle that is verified or the actual object.

If a reference cast is desired, i.e. a different type of handle to the same object instance, then the opCast method should be implemented instead. The compiler will attempt to rewrite an expression cast<type>(expr) as expr.opCast(), and chose the opCast overload that returns a handle of the desired type. Here too the opImplCast can be implemented instead if the reference cast is allowed to be performed implicitly by the compiler.

  class MyObjA
  {
    MyObjB @objB;
    MyObjC @objC;
    MyObjB @opCast() { return objB; }
    MyObjC @opImplCast() { return objC; }
    const MyObjB @opCast() const { return objB; }
    const MyObjC @opImplCast() const { return objC; }
  }

An example where the opCast/opImplCast operator overloads come in handy is when extending a type without directly inheriting from it.

See also

Type conversions, Inheriting from application registered class

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: Protected and private class members</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

Protected and private class members

Class members can be declared as protected or private to control where they can be accessed from. Protected members cannot be accessed from outside the class. Private members additionally cannot be accessed by derived classes.

This can be useful in large programs where you wish to avoid programmer errors where properties or methods are inappropriately used.

  // A class with private members
  class MyBase
  {
    // The following are public members
    void PublicFunc()
    {
      // The class can access its own protected and private members
      ProtectedProp = 0; // OK
      ProtectedFunc();   // OK
      PrivateProp = 0;   // OK
      PrivateFunc();     // OK
    }

    int PublicProp;

    // The following are protected members
    protected void ProtectedFunc() {}
    protected int ProtectedProp;

    // The following are private members
    private void PrivateFunc() {}
    private int PrivateProp;
  }

  class MyDerived : MyBase
  {
    void Func()
    {
      // The derived class can access the protected members
      // of the base class but not the private members
      ProtectedProp = 1; // OK
      ProtectedFunc();   // OK
      PrivateProp = 1;   // Error
      PrivateFunc();     // Error
    }
  }

  void GlobalFunc()
  {
    MyBase obj;

    // Public members can be accessed normally
    obj.PublicProp = 0;  // OK
    obj.PublicFunc();    // OK

    // Accessing protected and private members will give a compiler error
    obj.ProtectedProp = 0; // Error
    obj.ProtectedFunc();   // Error
    obj.PrivateProp = 0;   // Error
    obj.PrivateFunc();     // Error
  }

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: Property accessors</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

Property accessors

Note

The application can optionally turn off support for property accessors, so you need to verify your application's manual to determine if this is supported for your application or not.

Many times when working with properties it is necessary to make sure specific logic is followed when accessing them. An example would be to always send a notification when a property is modified, or computing the value of the property from other properties. By implementing property accessor methods for the properties this can be implemented by the class itself, making it easier for the one who accesses the properties.

In AngelScript property accessors are declared with the following syntax:

  class MyObj
  {
    // A virtual property with accessors
    int prop
    {
      get const
      {
        // The actual value of the property could be stored
        // somewhere else, or even computed at access time.
        return realProp;
      }
      set
      {
        // The new value is stored in a hidden parameter appropriately called 'value'.
        realProp = value;
      }
    }

    // The actual value can be stored in a member or elsewhere.
    // It is actually possible to use the same name for the real property, if so is desired.
    private int realProp;
  }

Behind the scene the compiler transforms this into two methods with the name of the property and the prefixes get_ and set_, and with the function decorator 'property'. The following generates the equivalent code, and is perfectly valid too:

  class MyObj
  {
    int get_prop() const property { return realProp; }
    void set_prop(int value) property { realProp = value; }
    private int realProp;
  }

If you implement the property accessors by explicitly writing the two methods you must make sure the return type of the get accessor and the parameter type of the set accessor match, otherwise the compiler will not know which is the correct type to use.

For interfaces the first alternative is usually the preferred way of declaring the property accessors, as it gets quite short and easy to read.

  interface IProp
  {
    int prop { get const; set; }
  }

You can also leave out either the get or set accessor. If you leave out the set accessor, then the property will be read-only. If you leave out the get accessor, then the property will be write-only.

Property accessors can also be implemented for global properties, which follows the same rules, except the functions are global.

When the property accessors have been declared it is possible to access them like ordinary properties, and the compiler will automatically expand the expressions to the appropriate function calls, either set_ or get_ depending on how the property is used in the expression.

  void Func()
  {
    MyObj obj;

    // Set the property value just like a normal property.
    // The compiler will convert this to a call to set_prop(10000).
    obj.prop = 10000;

    // Get the property value just a like a normal property.
    // The compiler will convert this to a call to get_prop().
    assert( obj.prop == 1000 );
  }

Observe that as property accessors are actually a pair of methods rather than direct access to the value, some restrictions apply as to how they can be used in expressions that inspect and mutate in the same operation. Compound assignments can be used on property accessors if the owning object is a reference type, but not if the owning object is a value type. This is because the compiler must be able to guarantee that the object stays alive between the two calls to the get accessor and set accessor.

The increment and decrement operators are currently not supported.

In such cases the expression must be expanded so that the read and write operation are performed separately, e.g. the increment operator must be rewritten as follows:

  a++;     // will not work if a is a virtual property
  a += 1;  // this is OK, as long as the owner of the virtual
           // property is a reference type or the property is global

Indexed property accessors

Property accessors can be used to emulate a single property or an array of properties accessed through the index operator. Property accessors for indexed access work the same way as ordinary property accessors, except that they take an index argument. The get accessor should take the index argument as the only argument, and the set accessor should take the index argument as the first argument, and the new value as the second argument.

  string firstString;
  string secondString;

  // A global indexed get accessor
  string get_stringArray(int idx) property
  {
    switch( idx )
    {
    case 0: return firstString;
    case 1: return secondString;
    }
    return "";
  }

  // A global indexed set accessor
  void set_stringArray(int idx, const string &in value) property
  {
    switch( idx )
    {
    case 0: firstString = value; break;
    case 1: secondString = value; break;
    }
  }

  void main()
  {
    // Setting the value of the indexed properties
    stringArray[0] = "Hello";
    stringArray[1] = "World";

    // Reading the value of the indexed properties
    print(StringArray[0] + " " + stringArray[1] + "\n");
  }

Compound assignments currently doesn't work for indexed properties.

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: 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

Functions

Functions are declared globally, and consists of a signature where the types of the arguments and the return value is defined, and a body where the implementation is declared.

Function declaration

Parameter references

Return references

Function overloading

Default arguments

Anonymous functions

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


code:
var doc_script_func =
[
    [ "Function declaration", "doc_script_func_decl.html", null ],
    [ "Parameter references", "doc_script_func_ref.html", null ],
    [ "Return references", "doc_script_func_retref.html", [
      [ "References to global variables are allowed", "doc_script_func_retref.html#doc_script_retref_global", null ],
      [ "References to class members are allowed", "doc_script_func_retref.html#doc_script_refref_member", null ],
      [ "Can't return reference to local variables", "doc_script_func_retref.html#doc_script_retref_local", null ],
      [ "Can't use expressions with deferred parameters", "doc_script_func_retref.html#doc_script_retref_deferred", null ],
      [ "Can't use expressions that rely on local objects", "doc_script_func_retref.html#doc_script_refref_cleanup", null ]
    ] ],
    [ "Function overloading", "doc_script_func_overload.html", null ],
    [ "Default arguments", "doc_script_func_defarg.html", null ],
    [ "Anonymous functions", "doc_script_anonfunc.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: Function declaration</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

Function declaration

Global functions provide the mean to implement routines that should operate on some input and produce a result. The functions themselves do not keep any memory, though they can update global variables, or memory passed by reference.

The function is always declared together with the function body. There is no need to declare function prototypes, as the function is globally visible regardless where it has been declared.

  // A simple function declaration
  int AFunction(int a, int b)
  {
    // Implement the function logic here
    return a + b;
  }

The type of the return value should be specified before the name of the function. If the function doesn't return anything the type should be defined as 'void'. After the function name, the list of parameters is specified between parenthesis. Each parameter is defined by its type and name.

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: Default arguments</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

Default arguments

Sometimes implementing different functions for each overload is unnecessary when the difference can be provided with a default value to a parameter. This is where default arguments come in handy.

By defining default arguments in the declaration of the function, the script doesn't have to provide these values specifically when calling the function as the compiler will automatically fill in the default arguments.

  void Function(int a, int b = 1, string c = "")
  {
    // Inside the function the arguments work normally
  }

  void main()
  {
    // Default arguments doesn't have to be informed
    // The following three calls produce the exact same result
    Function(0);
    Function(0,1);
    Function(0,1,"");
  }

When defining a default argument to one of the parameters, all subsequent parameters must have a default argument too.

The default argument expression can include references to variables or call functions, but only if the variables or functions are visible in the global scope.

  int myvar = 42;
  void Function(int a, int b = myvar) {}
  void main()
  {
    int myvar = 1;
    Function(1);    // This will use the global myvar and not the local myvar
  }

The special 'void' expression can be used as default argument to make an optional output parameter.

  void func(int &out output = void) { output = 42; }

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: Function overloading</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

Function overloading

Function overloading happens when more than one function with the same name is declared with different parameters. This is a useful feature when an operation needs to be able to work with different types of input, yet produce similar result.

The compiler is able to resolve which function to call by matching the type of each argument expression to the function parameter, and eliminating the functions where there is no possible conversion available. The compiler will do this for each argument from first to last. When all arguments have been evaluated only one function should be the best match, otherwise the compiler will give an error about the impossibility to determine the correct function to call.

The type of conversion that needs to be performed on the argument to get to the type of the parameter determines how well a function matches. The following list gives the order of how one type of conversion compares to another.

no conversion needed

conversion to const

conversion of enum to integer of same size

conversion of enum to integer of different size

size of primitive type increases

size of primitive type decreases

signed integer to unsigned integer conversion

unsigned integer to signed integer conversion

integer type to float type

float type to integer type

reference cast

object to primitive conversion

conversion to object

variable argument type

Observe that it is not possible to create overloads where the only difference is the return type. This is because the return type is not part of the selection criteria that the compiler uses to determine which function to call, the return type is just the result of the called function.

  void Function(int a, float b, string c) {}
  void Function(string a, int b, float c) {}
  void Function(float a, string b, int c) {}

  void main()
  {
    Function(1, 2.5f, 'a');  // Will call the first overload
    Function('a', 1, 2.5f);  // Will call the second overload
    Function(2.5f, 'a', 1);  // Will call the third overload
  }

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: Parameter 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

Parameter references

The parameters and return value can be of any type that can also be used for variable declarations. In addition, it is also possible to make a function take a value by reference, i.e. rather than a copy of the original value, the parameter will refer to the value.

Parameter references are used mainly for two purposes; a means of providing additional output from the function, or as a more performatic way of passing values.

In AngelScript it is necessary to specify the intention of the parameter reference, i.e. if it is meant as input, output, or both. This is necessary in order for the compiler to prepare the reference in a way that it cannot be invalidated due to some action during the processing of the function.

Input references are written as &in. As the reference is meant as input only, the actual value it refers to normally is a copy of the original so the function doesn't accidentally modify the original value. These are not commonly used, as they provide little benefit over passing arguments by value. Only in some circumstances can the performance be improved, especially if the parameter is declared as const too.

Output references are written as &out. These references are meant to allow the function to return additional values. When going in to the function, the reference will point to an uninitialized value. After the function returns, the value assigned by the function will be copied to the destination determined by the caller.

When the reference is meant as both input and output, it is declared as &inout, or just &. In this case the reference will point to the actual value. Only reference types, i.e. that can have handles to them, are allowed to be passed as inout references. This is because in order to guarantee that the reference will stay valid during the entire execution of the function, the value must be located in the memory heap.

  void Function(const int &in a, int &out b, Object &c)
  {
    // Assigning an output value to the output reference
    b = a;

    // The object is an inout reference and refers to the real object
    c.DoSomething();
  }

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: Return 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

Return references

A function can also return references, which will allow the caller to modify the value pointed to by the reference. To declare a function that return a reference include the & symbol between the return type and name of the function. Add const before the type if the reference should be read only, i.e. it shouldn't be possible to modify the value it points to.

  int property;
  int &Function()
  {
    // Return a reference to the property
    return property;
  }

  void main()
  {
    // Modify the value pointed to by the returned reference
    Function() = 1;
  }

Due to the need to guarantee that the reference is valid even after the function returns to the caller there exist certain restrictions. You don't need to try to remember these restrictions as the compiler will give an error if you they are violated, but if you do encounter a compile error when returning a reference it will be good to understand why it is happening so that you can determine how to avoid it.

References to global variables are allowed

As a global variable is in the global scope, the lifetime of the variable is longer than the scope of the function. A function can thus return a reference to a global variable, or even member of an object reached through a global variable.

References to class members are allowed

A class method can return a reference to a class property of the same object, because the caller is required to hold a reference to the object it is known that the member will exist even after the method returns.

The class method is also allowed to return reference to global variables, just like any other function.

Can't return reference to local variables

Because local variables must be freed when the function exits, it is not allowed to return a reference to them. The same is also true for any parameters that the function received. The parameters are also cleaned up when the function exits, so they too cannot be returned by reference.

Can't use expressions with deferred parameters

For some function calls with arguments, there may be a necessary processing of the arguments after the function call returned, e.g. to clean up the input object, or to assign the output parameters. If the function that was called is returning a reference, then that reference cannot in turn be returned again, as it may be invalidated by the deferred evaluation of the arguments.

Can't use expressions that rely on local objects

All local objects must be cleaned up before a function exits. For functions that return references this clean-up happens before the return expression is evaluated, otherwise the cleanup of the local objects may accidentally invalidate the reference. For this reason it is not possible to use expressions that rely on local objects to evaluate the reference that should be returned.

Primitive values can be used though, as these do not require cleanup upon exit.

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: Global entities</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

Global entities

All global declarations share the same namespace so their names may not conflict. This includes extended data types and built-in functions registered by the host application. Also, all declarations are visible to all, e.g. a function to be called does not have to be declared above the function that calls it.

Functions

Variables

Virtual properties

Script classes

Interfaces

Mixin class

Enums

Funcdefs

Typedefs

Namespaces

Imports

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


code:
var doc_script_global =
[
    [ "Functions", "doc_global_func.html", null ],
    [ "Variables", "doc_global_variable.html", null ],
    [ "Virtual properties", "doc_global_virtprop.html", null ],
    [ "Script classes", "doc_global_class.html", null ],
    [ "Interfaces", "doc_global_interface.html", null ],
    [ "Mixin class", "doc_script_mixin.html", null ],
    [ "Enums", "doc_global_enums.html", null ],
    [ "Funcdefs", "doc_global_funcdef.html", null ],
    [ "Typedefs", "doc_global_typedef.html", null ],
    [ "Namespaces", "doc_global_namespace.html", null ],
    [ "Imports", "doc_global_import.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: Object handles</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

Object handles

An object handle is a type that can hold a reference to an object. With object handles it is possible to declare more than one variables that refer to the same physical object.

Not all types allow object handles to be used. None of the primitive data types, bool, int, float, etc, can have object handles. Object types registered by the application may or may not allow object handles, depending on how they have been registered.

See also

Object handles to the application

General usage

An object handle is declared by appending the @ symbol to the data type.

  object@ obj_h;

This code declares the object handle obj and initializes it to null, i.e. it doesn't hold a reference to any object.

In expressions variables declared as object handles are used the exact same way as normal objects. But you should be aware that object handles are not guaranteed to actually reference an object, and if you try to access the contents of an object in a handle that is null an exception will be raised.

  object obj;
  object@ obj_h;
  obj.Method();
  obj_h.Method();

Operators like = or any other operator registered for the object type work on the actual object that the handle references. These will also throw an exception if the handle is empty.

  object obj;
  object@ obj_h;
  obj_h = obj;

When you need to make an operation on the actual handle, you should prepend the expression with the @ symbol. Setting the object handle to point to an object is for example done like this:

  object obj;
  object@ obj_h;
  @obj_h = @obj;

Note that the compiler can often implicitly determine that it is the handle of the object that is needed rather than the actual object itself. In these cases it is not necessary to explicitly prepend the expression with @.

An object handle can be compared against another object handle (of the same type) to verify if they are pointing to the same object or not. It can also be compared against null, which is a special keyword that represents an empty handle. This is done using the identity operator, is.

  object@ obj_a, obj_b;
  if( obj_a is obj_b ) {}
  if( obj_a !is null ) {}

Observe, the == and != operators will do a value comparison on the objects referred to by the handles using the opEquals or opCmp operator overloads. Though, if the expressions are prepended with @ the operators will have the same function as is and !is.

Object life times

An object's life time is normally for the duration of the scope the variable was declared in. But if a handle outside the scope is set to reference the object, the object will live on until all object handles are released.

  object@ obj_h;
  {
    object obj;
    @obj_h = @obj;

    // The object would normally die when the block ends,
    // but the handle is still holding a reference to it
  }

  // The object still lives on in obj_h ...
  obj_h.Method();

  // ... until the reference is explicitly released
  // or the object handle goes out of scope
  @obj_h = null;

Object relations and polymorphing

Object handles can be used to write common code for related types, by means of inheritance or interfaces. This allows a handle to an interface to store references to all object types that implement that interface, similarly a handle to a base class can store references to all object types that derive from that class.

  interface I {}
  class A : I {}
  class B : I {}

  // Store reference in handle to interface
  I @i1 = A();
  I @i2 = B();

  void function(I @i)
  {
    // Functions implemented by the interface can be
    // called directly on the interface handle. But if
    // special treatment is need for a specific type, a
    // cast can be used to get a handle to the true type.
    A @a = cast<A>(i);
    if( a !is null )
    {
      // Access A's members directly
      ...
    }
    else
    {
      // The object referenced by i is not of type A
      ...
    }
  }

Const handles

Sometimes it is necessary to hold handles to objects that shouldn't be allowed to be modified. This is done by prefixing the type with 'const', e.g.

  obj @a;                      // handle to modifiable object
  const obj @b;                // handle to non-modifiable object

A handle to a non-modifiable object can refer to both modifiable objects and non-modifiable objects, but the script will not allow the object to be modified through that handle, nor allow the handle to be passed to another handle that would allow modifications.

This syntax is not to be confused with handles that are themselves read-only, i.e. the handle cannot be re-assigned to refer to a different object. Read-only handles like this are declared by adding the 'const' keyword as a suffix after the '@' symbol.

  obj @ const c = obj();       // read-only handle to a modifiable object
  const obj @ const d = obj(); // read-only handle to a non-modifiable object

A read-only handle can only be initialized when declared.

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: Mixin class</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

Mixin class

As multiple inheritance is not available, it may sometimes be necessary to implement identical code in multiple classes. When this is necessary it is recommended to use mixin classes to avoid writing the identical code in multiple places.

Mixin classes allows a script to declare a partial class structure that will be included into multiple different class declarations. The mixin classes themselves are not real types and cannot be instanciated.

When a mixin class is included into a class declaration, the properties and methods that were declared in the mixin class will be automatically replicated into the class.

  // Declare a mixin class
  mixin class MyMixin
  {
    void SomeMethod() { property++; }
    int property;
  }

  // Include the mixin class into the class to receive the methods and properties
  class MyClass : MyMixin
  {
    int OtherMethod()
    {
      SomeMethod();
      return property;
    }
  }

Properties and methods that have already been explicitly declared in the class will not be included again. This way the mixin class can provide a default implementation that can be overridden by the class that includes the mixin.

The class methods included from a mixin class will be compiled in the context of the class that included it, so it is possible for a mixin class method to refer to properties and other methods that are not declared in the mixin class if the class that includes the mixin class provides those.

  mixin class MyMixin
  {
    void MethodA() { print("Default behaviour"); }
    void MethodB() { property++; }
  }

  class MyClass : MyMixin
  {
    // Override the default behaviour in MethodA
    void MethodA() { print("Overridden behaviour"); }

    // Declare the property that will be used by MethodB
    int property;
  }

Mixin class methods override inherited methods from base classes, just as if the included method had been implemented in the derived class directly. Mixin class properties on the other hand are not included if the property is already inherited from a base class.

  class MyBase
  {
    void MethodA() { print("Base behaviour"); }
    int property;
  }

  mixin class MyMixin
  {
    void MethodA() { print("Mixin behaviour"); }
    float property;
  }

  // Inheriting from base class and including mixin.
  // MyClass ends up with the property from the base
  // class and the method from the mixin class.
  class MyClass : MyBase, MyMixin
  {
  }

A mixin class can inform a list of interfaces that has to be implemented by the script class that includes the mixin class. In this case the methods for the interfaces can optionally be provided by the mixin class itself, or left out to be implemented by the script class directly.

A mixin class cannot inherit from other classes.

  interface I
  {
    void a();
    void b();
  }

  mixin class M : I
  {
        // provide default implementation of a()
    void a() { print("hello from a");

    // leave the implementation of b() to the script class
  }

  class C : M
  {
    // a() is implemented by mixin class

        // b() has to be explicitly implemented by script class
        void b() { print("hello from b");
  }

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: Shared script entities</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

Shared script entities

If the application uses multiple script modules to control different parts of the application it may sometimes be beneficial to allow parts of the scripts to be shared between the script modules. The main benefits of shared entities is the reduced memory consumption, and the fact that the type of the shared entity is the same for the modules thus simplifying the information exchange between modules where this is used.

Shared entities have a restriction in that they cannot access non-shared entities because the non-shared entities are exclusive to the script module in which they were compiled.

How to declare shared entities

To declare a shared entity simply put the keyword 'shared' before the ordinary declaration, e.g.

  shared class Foo
  {
    void MethodInFoo(int b) { bar = b; }
    int bar;
  }

  shared void GlobalFunc() {}

If the script tries to access any non-shared entity from within the shared entity then the compiler will give an error message.

Obviously, in order to work the scripts in all modules that share the entity must implement the entity the same way. If this is not done, the compiler will give an error in the scripts that are compiled after the first script that implemented the shared entity.

The easiest way to guarantee that the implementation is the same is by using the same source file, but this is not a requirement.

External shared entities

An alternative to declaring the full shared entity in each module is to declared the shared entity that is known to have been compiled before as external. This can shorten the script, both reducing the size of the source code and the time to compile it.

To declare a shared entity as external, simply add the keyword 'external' before the declaration and end the statement with ';' after the signature that uniquely identifies the entity.

  external shared class Foo;
  external shared void GlobalFunc();

When compiling a shared entity declared as external and the shared entity hasn't been compiled in any other module before it, the compiler will give an error message.

What can be shared

Currently only the class, interface, function, enum, and funcdefs entities can be shared.

Future versions may allow global variables to be shared too.

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: Statements</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

Statements

Variable declarations

Expression statement

Conditions: if / if-else / switch-case

Loops: while / do-while / for

Loop control: break / continue

Return statement

Statement blocks

Try-catch blocks

Variable declarations

  int var = 0, var2 = 10;
  object@ handle, handle2;
  const float pi = 3.141592f;

Variables must be declared before they are used within the statement block, or any sub blocks. When the code exits the statement block where the variable was declared the variable is no longer valid.

A variable can be declared with or without an initial expression. If it is declared with an initial expression it, the expression must have the evaluate to a type compatible with the variable type.

Any number of variables can be declared on the same line separated with commas, where all variables then get the same type.

Variables can be declared as const. In these cases the value of the variable cannot be changed after initialization.

Variables of primitive types that are declared without an initial value, will have a random value. Variables of complex types, such as handles and object are initialized with a default value. For handles this is null, for objects this is what is defined by the object's default constructor.

Expression statement

  a = b;  // a variable assignment
  func(); // a function call

Any expression may be placed alone on a line as a statement. This will normally be used for variable assignments or function calls that don't return any value of importance.

All expression statements must end with a ;.

Conditions: if / if-else / switch-case

  if( condition )
  {
    // Do something if condition is true
  }

  if( value < 10 )
  {
    // Do something if value is less than 10
  }
  else
  {
    // Do something else if value is greater than or equal to 10
  }

If statements are used to decide whether to execute a part of the logic or not depending on a certain condition. The conditional expression must always evaluate to true or false.

It's possible to chain several if-else statements, in which case each condition will be evaluated sequencially until one is found to be true.

  switch( value )
  {
  case 0:
    // Do something if value equals 0, then leave
    break;

  case 2:
  case constant_value:
    // This will be executed if value equals 2 or the constant_value
    break;

  default:
    // This will be executed if value doesn't equal any of the cases
  }

If you have an integer (signed or unsigned) expression that have many different outcomes that should lead to different code, a switch case is often the best choice for implementing the condition. It is much faster than a series of ifs, especially if all of the case values are close in numbers.

Each case should be terminated with a break statement unless you want the code to continue with the next case.

The case value can be a constant variable that was initialized with a constant expression. If the constant variable was initialized with an expression that cannot be determined at compile time it cannot be used in the case values.

Loops: while / do-while / for

  // Loop, where the condition is checked before the logic is executed
  int i = 0;
  while( i < 10 )
  {
    // Do something
    i++;
  }

  // Loop, where the logic is executed before the condition is checked
  int j = 0;
  do
  {
    // Do something
    j++;
  } while( j < 10 );

For both while and do-while the expression that determines if the loop should continue must evaluate to either true or false. If it evaluates to true, the loop continues, otherwise it stops and the code will continue with the next statement immediately following the loop.

  // More compact loop, where condition is checked before the logic is executed
  for( int n = 0; n < 10; n++ )
  {
    // Do something
  }

The for loop is a more compact form of a while loop. The first part of the statement (until the first ;) is executed only once, before the loop starts. Here it is possible to declare a variable that will be visible only within the loop statement. The second part is the condition that must be satisfied for the loop to be executed. A blank expression here will always evaluate to true. The last part is executed after the logic within the loop, e.g. used to increment an iteration variable.

Multiple variables can be declared in the for loop, separated by ,. Likewise, multiple increment expressions can be used in the last part by separating them with ,.

Loop control: break / continue

  for(;;) // endless loop
  {
    // Do something

    // End the loop when condition is true
    if( condition )
      break;
  }

break terminates the smallest enclosing loop statement or switch statement.

  for(int n = 0; n < 10; n++ )
  {
    if( n == 5 )
      continue;

    // Do something for all values from 0 to 9, except for the value 5
  }

continue jumps to the next iteration of the smallest enclosing loop statement.

Return statement

  float valueOfPI()
  {
    return 3.141592f; // return a value
  }

Any function with a return type other than void must be finished with a return statement where expression evaluates to the same data type as the function return type. Functions declared as void can have return statements without any expression to terminate early.

Statement blocks

  {
    int a;
    float b;

    {
      float a; // Override the declaration of the outer variable
               // but only within the scope of this block.

      // variables from outer blocks are still visible
      b = a;
    }

    // a now refers to the integer variable again
  }

A statement block is a collection of statements. Each statement block has its own scope of visibility, so variables declared within a statement block are not visible outside the block.

Try-catch blocks

 {
   try
   {
     DoSomethingThatMightThrowException();

     // This is not executed if an exception was thrown
   }
   catch
   {
     // This is executed if an exception was thrown
   }
  }

A try-catch block can be used if you're executing some code that might throw an exception and you want to catch that exception and continue with the exception rather than just abort the script.

Exceptions can occur for various reasons, some examples include, accessing null pointers in uninitialized handles, division by zero, or exceptions raised from application registered functions. In some cases exceptions are intentionally raised by the script to interrupt some execution.

See also

Exception handling

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: Standard 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

Standard library

This pages describes the standard library provided by the AngelScript SDK. The applications that use AngelScript may or may not expose the standard library to the scripts. Always consult the application's manual for information on the API it exposes.

Exception handling

string

array

dictionary

ref

weakref

datetime

Co-routines

file

filesystem

System functions

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


code:
var doc_script_stdlib =
[
    [ "Exception handling", "doc_script_stdlib_exception.html", [
      [ "Functions", "doc_script_stdlib_exception.html#try_func", null ]
    ] ],
    [ "string", "doc_script_stdlib_string.html", [
      [ "Supporting string object and functions", "doc_script_stdlib_string.html#doc_datatypes_strings_addon", [
        [ "Operators", "doc_script_stdlib_string.html#doc_datatypes_strings_addon_ops", null ],
        [ "Methods", "doc_script_stdlib_string.html#doc_datatypes_strings_addon_mthd", null ],
        [ "Functions", "doc_script_stdlib_string.html#doc_datatypes_strings_addon_funcs", null ]
      ] ]
    ] ],
    [ "array", "doc_datatypes_arrays.html", [
      [ "Supporting array object", "doc_datatypes_arrays.html#doc_datatypes_arrays_addon", [
        [ "Operators", "doc_datatypes_arrays.html#doc_datatypes_array_addon_ops", null ],
        [ "Methods", "doc_datatypes_arrays.html#doc_datatypes_array_addon_mthd", null ],
        [ "Script example", "doc_datatypes_arrays.html#doc_datatypes_array_addon_example", null ]
      ] ]
    ] ],
    [ "dictionary", "doc_datatypes_dictionary.html", [
      [ "Supporting dictionary object", "doc_datatypes_dictionary.html#doc_datatypes_dictionary_addon", [
        [ "Operators", "doc_datatypes_dictionary.html#doc_datatypes_dictionary_addon_ops", null ],
        [ "Methods", "doc_datatypes_dictionary.html#doc_datatypes_dictionary_addon_mthd", null ]
      ] ],
      [ "Supporting dictionaryValue object", "doc_datatypes_dictionary.html#doc_datatypes_dictionaryValue_addon", [
        [ "Operators", "doc_datatypes_dictionary.html#doc_datatypes_dictionaryValue_addon_ops", null ]
      ] ]
    ] ],
    [ "ref", "doc_datatypes_ref.html", [
      [ "Supporting ref object", "doc_datatypes_ref.html#doc_datatypes_ref_addon", [
        [ "Operators", "doc_datatypes_ref.html#doc_datatypes_ref_addon_ops", null ]
      ] ]
    ] ],
    [ "weakref", "doc_datatypes_weakref.html", [
      [ "Supporting weakref object", "doc_datatypes_weakref.html#doc_datatypes_weakref_addon", [
        [ "Constructors", "doc_datatypes_weakref.html#doc_datatypes_weakref_addon_construct", null ],
        [ "Operators", "doc_datatypes_weakref.html#doc_datatypes_weakref_addon_ops", null ],
        [ "Methods", "doc_datatypes_weakref.html#doc_datatypes_weakref_addon_mthd", null ]
      ] ]
    ] ],
    [ "datetime", "doc_script_stdlib_datetime.html", [
      [ "Supporting datetime object", "doc_script_stdlib_datetime.html#doc_datatype_datetime_addon", [
        [ "Constructors", "doc_script_stdlib_datetime.html#doc_addon_datetime_2_construct", null ],
        [ "Methods", "doc_script_stdlib_datetime.html#doc_addon_datetime_2_methods", null ],
        [ "Operators", "doc_script_stdlib_datetime.html#doc_addon_datetime_2_ops", null ]
      ] ]
    ] ],
    [ "Co-routines", "doc_script_stdlib_coroutine.html", [
      [ "Functions", "doc_script_stdlib_coroutine.html#doc_script_stdlib_coroutine_1", null ]
    ] ],
    [ "file", "doc_script_stdlib_file.html", [
      [ "Supporting file object", "doc_script_stdlib_file.html#doc_script_stdlib_file_1", [
        [ "Methods", "doc_script_stdlib_file.html#doc_script_stdlib_file_1_1", null ],
        [ "Properties", "doc_script_stdlib_file.html#doc_script_stdlib_file_1_2", null ]
      ] ]
    ] ],
    [ "filesystem", "doc_script_stdlib_filesystem.html", [
      [ "Supporting filesystem object", "doc_script_stdlib_filesystem.html#doc_script_stdlib_filesystem_1", [
        [ "Methods", "doc_script_stdlib_filesystem.html#doc_script_stdlib_filesystem_1_1", null ]
      ] ]
    ] ],
    [ "System functions", "doc_script_stdlib_system.html", [
      [ "Functions", "doc_script_stdlib_system.html#doc_script_stdlib_system_1", 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: Co-routines</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

Co-routines

Note

Support for co-routines is only available in the scripts if the application registers support for it.

Functions

funcdef void coroutine(dictionary@)

 void createCoRoutine(coroutine @, dictionary @)

This function is used to create a co-routine. The co-routine will initiate in a yielded state, i.e. it will only begin execution once the control is given to it by the current thread.

Multiple co-routines can be created, and they will each take turn to execute in round-robin fashion.

void yield()

Yields control of the execution for the next co-routine in the queue.

When a co-routine receives control it will resume execution from the last call to yield, or the entry point if this is the first time the co-routine is allowed to execute.

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: datetime</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

datetime

Note

datetime is only available in the scripts if the application registers support for it.

The datetime type represents a calendar date and time. It can be used to do math operations with dates, such as comparing two dates, determining the difference between dates, and addition/substraction on dates to form new dates.

It can also be used to get the current system time and thus allow measuring time for tasks, albeit with a rather low precision of seconds only.

Supporting datetime object

Constructors

datetime()

 datetime(const datetime &in other)

 datetime(uint y, uint m, uint d, uint h = 0, uint mi = 0, uint s = 0)

The default constructor initializes the object with the current system time in the universal time zone (UTC). If you need to consider a specific timezone with or without daylight savings then remember to adjust the time accordingly by adding the number of seconds for the difference.

The copy constructor copíes the content of the other object.

The set constructor initializes the object with the given date and time.

Methods

uint get_year() const property

Returns the year of the date stored in the object.

uint get_month() const property

Returns the month of the date stored in the object. The range is 1 to 12, i.e. 1 is January, 12 is December, and so on.

uint get_day() const property

Returns the day of the month of the date stored in the object.

uint get_hour() const property

Returns the hour of the time stored in the object. The range is 0 to 23.

uint get_minute() const property

Returns the minute of the time stored in the object. The range is 0 to 59.

uint get_second() const property

Returns the second of the time stored in the object. The range is 0 to 59.

bool setDate(uint year, uint month, uint day)

 bool setTime(uint hour, uint minute, uint second)

Sets the date or time. Returns true if the specified date or time is valid. Does not modify the object if not valid.

Operators

= assignment

The assignment operator copies the content of the other object.

- difference

When subtracting one datetime object from another the result is the number of seconds between them.

+ add

 - subtract

 += add assign

 -= subtract assign

The datetime object can be added or subtracted with seconds to form a new datetime object.

==, != equality

 <, <=, >=, > comparison

The datetime object can be compared for equality or relativity.

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: Exception handling</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

Exception handling

Note

The standard throw and getExceptionInfo are only provided if the application registers them.

Functions

void throw(const string &in exception)

Explicitly throw an exception. The string should identify the type of exception, for logging or treating.

string getExceptionInfo()

Get the exception string for the last exception thrown.

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