### Example Usage: Building a Module and Accessing Metadata Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_build.html Demonstrates the C++ usage of CScriptBuilder to start a module, add script sections, build the module, and then retrieve metadata strings for global variables. ```c++ CScriptBuilder builder; int r = builder.StartNewModule(engine, "my module"); if( r >= 0 ) r = builder.AddSectionFromMemory(script); if( r >= 0 ) r = builder.BuildModule(); if( r >= 0 ) { // Find global variables that have been marked as editable by user asIScriptModule *mod = engine->GetModule("my module"); int count = mod->GetGlobalVarCount(); for( int n = 0; n < count; n++ ) { vector metadata = builder.GetMetadataStringForVar(n); for( int m = 0; m < metadata.size(); m++ ) { if( metadata[m] == "editable" ) { // Show the global variable in a GUI ... } } } } ``` -------------------------------- ### C++ 'any' Example Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_any.html Example demonstrating how to use the CScriptAny type within C++ code. ```APIDOC ## C++ 'any' Example Usage ```cpp CScriptAny *myAny; int typeId = engine->GetTypeIdByDecl("string@"); CScriptString *str = new CScriptString("hello world"); myAny->Store((void*)&str, typeId); myAny->Retrieve((void*)&str, typeId); ``` ``` -------------------------------- ### Array Manipulation and Sorting Example Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_datatypes_arrays.html A comprehensive script example demonstrating array initialization, insertion, removal, sorting, and iteration to calculate a sum. ```angelscript int main() { array arr = {1,2,3}; // 1,2,3 arr.insertLast(0); // 1,2,3,0 arr.insertAt(2,4); // 1,2,4,3,0 arr.removeAt(1); // 1,4,3,0 arr.sortAsc(); // 0,1,3,4 int sum = 0; foreach( auto value : arr ) sum += value; return sum; } ``` -------------------------------- ### Script 'any' Example Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_any.html Example demonstrating how to use the 'any' type within AngelScript scripts. ```APIDOC ## Script 'any' Example Usage ``` int value; obj object; obj @handle; any a,b,c; a.store(value); // store the value b.store(@handle); // store an object handle c.store(object); // store a copy of the object a.retrieve(value); // retrieve the value b.retrieve(@handle); // retrieve the object handle c.retrieve(object); // retrieve a copy of the object ``` ``` -------------------------------- ### CScriptAny Store and Retrieve Example in C++ Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_any.html Example of using CScriptAny in C++ to store and retrieve a string handle, demonstrating type registration and value manipulation. ```c++ CScriptAny *myAny; int typeId = engine->GetTypeIdByDecl("string@"); CScriptString *str = new CScriptString("hello world"); myAny->Store((void*)&str, typeId); myAny->Retrieve((void*)&str, typeId); ``` -------------------------------- ### asIScriptEngine::BeginConfigGroup Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Starts a new dynamic configuration group, allowing for isolated registration of types and functions. ```APIDOC ## asIScriptEngine::BeginConfigGroup ### Description Starts a new dynamic configuration group. ### Method virtual int BeginConfigGroup(const char *groupName) ### Parameters #### Path Parameters - **groupName** (const char *) - The name of the configuration group to start. ``` -------------------------------- ### Dictionary Initialization and Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_datatypes_dictionary.html Demonstrates how to initialize a dictionary with key-value pairs and access/modify its elements using get, set, and the index operator. ```APIDOC ## Dictionary Initialization and Usage ### Description Dictionaries store key-value pairs where keys are strings and values can be of any type. They can be initialized with a list of pairs and elements can be accessed or modified using `get`, `set`, or the index operator `[]`. ### Code Example ``` obj object; obj @handle; // Initialize with a list dictionary dict = {{'one', 1}, {'object', object}, {'handle', @handle}}; // Examine and access the values through get or set methods ... if( dict.exists('one') ) { // get returns true if the stored type is compatible with the requested type bool isValid = dict.get('handle', @handle); if( isValid ) { dict.delete('object'); dict.set('value', 1); } } ``` ### Index Operator Usage ``` // Read and modify an integer value int val = int(dict['value']); dict['value'] = val + 1; // Read and modify a handle to an object instance @handle = cast(dict['handle']); if( handle is null ) @dict['handle'] = object; ``` ``` -------------------------------- ### ScriptGrid Example Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_grid.html Demonstrates initializing a 2D grid with values and defining a function to check grid cell properties. ```angelscript // Initialize a 5x5 map grid map = {{1,0,1,1,1}, {0,0,1,0,0}, {0,1,1,0,1}, {0,1,1,0,1}, {0,0,0,0,1}}; // A function to verify if the next area is walkable bool canWalk(uint x, uint y) { // If the map in the destination is // clear, it is possible to wark there return map[x,y] == 0; } ``` -------------------------------- ### Script Grid Example Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_grid.html Demonstrates how to use the `grid` object in script code, including initialization and accessing elements. ```APIDOC ## Example Usage in Script ### Description This example shows how to declare, initialize, and use a `grid` object in AngelScript. It includes a function `canWalk` that utilizes the grid's index operator to check cell values. ### Code Example ``` // Initialize a 5x5 map grid map = {{1,0,1,1,1}, {0,0,1,0,0}, {0,1,1,0,1}, {0,1,1,0,1}, {0,0,0,0,1}}; // A function to verify if the next area is walkable bool canWalk(uint x, uint y) { // If the map in the destination is // clear, it is possible to wark there return map[x,y] == 0; } ``` ``` -------------------------------- ### asIScriptEngine::BeginConfigGroup Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_engine.html Starts a new dynamic configuration group. This group can be configured to be visible only to specific modules and can be removed when no longer needed. ```APIDOC ## BeginConfigGroup() ### Description Starts a new dynamic configuration group. This group can be configured to be visible only to specific modules and can be removed when no longer needed. ### Method virtual int BeginConfigGroup(const char * _groupName_) ### Parameters * **_groupName_** (const char *) - Required - The name of the configuration group. ### Returns A negative value on error. ### Return values * **asNAME_TAKEN**: Another group with the same name already exists. * **asNOT_SUPPORTED**: Nesting configuration groups is not supported. ``` -------------------------------- ### Example Script with Include Directive Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_build.html Demonstrates how to use the #include directive in an AngelScript file to incorporate code from another script, such as common functions. ```angelscript #include "commonfuncs.as" void main() { // Call a function from the included file CommonFunc(); } ``` -------------------------------- ### Constructor Implementation for Value Type Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html Example of a constructor function for a value type using placement-new to initialize memory. ```c++ void Constructor(void *memory) { // Initialize the pre-allocated memory by calling the // object constructor with the placement-new operator new(memory) Object(); } ``` -------------------------------- ### Function Overloading Example Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_func_overload.html Demonstrates how to declare and call overloaded functions with different parameter types. The compiler selects the appropriate function based on the argument types provided. ```angelscript 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 } ``` -------------------------------- ### AngelScript Script Example Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_hello_world.html A simple AngelScript function that calls the registered 'print' function to output 'Hello world' to the console. This demonstrates basic script execution. ```angelscript void main() { print("Hello world\n"); } ``` -------------------------------- ### Example Usage of RegisterObjectProperty with asOFFSET Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_engine.html Demonstrates how to register a float property named 'prop' of 'MyType' using `RegisterObjectProperty` and the `asOFFSET` macro. ```c++ struct MyType {float prop;}; r = engine->RegisterObjectProperty("MyType", "float prop", asOFFSET(MyType, prop))); ``` -------------------------------- ### Example Usage of weakref Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_datatypes_weakref.html Illustrates how to use weakref and const_weakref to reference objects, and how the references behave when the original objects are no longer strongly referenced. ```APIDOC ``` class MyClass {} MyClass @obj1 = MyClass(); // Keep a weakref to the object weakref r1(obj1); // Keep a weakref to a readonly object const_weakref r2(obj1); // As long as there is a strong reference to the object, // the weakref will be able to return a handle to the object MyClass @obj2 = r1.get(); assert( obj2 !is null ); // After all strong references are removed the // weakref will only return null @obj1 = null; @obj2 = null; const MyClass @obj3 = r2.get(); assert( obj3 is null ); ``` ``` -------------------------------- ### Listen, Accept, Receive, and Send with Socket Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_socket.html Demonstrates how to set up a server socket to listen for connections, accept a client, receive data, and send a response. Includes timeout handling for accept and receive operations. ```angelscript // Start listening for incoming connections socket server; server.listen(39000); // Wait for a client to connect socket @client = server.accept(10*1000000); // Timeout of 10 seconds if( client !is null ) { // Receive a message string pkg = client.receive(1*1000000); // 1 second time out // Return the same message to the client client.send(pkg); } ``` -------------------------------- ### Registering Array Accessors as Object Methods Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_reg_objprop.html Expose C++ array members to scripts by registering proxy functions as property accessors. This example shows how to register 'get' and 'set' methods for an array. ```c++ struct MyStruct { int array[16]; }; // Write a couple of proxy int MyStruct_get_array(unsigned int idx, MyStruct *o) { if( idx >= 16 ) return 0; return o->array[idx]; } void MyStruct_set_array(unsigned int idx, int value, MyStruct *o) { if( idx >= 16 ) return; o->array[idx] = value; } // Register the proxy functions as member methods r = engine->RegisterObjectMethod("mytype", "int get_array(uint) property", asFUNCTION(MyStruct_get_array), asCALL_CDECL_OBJLAST); assert( r >= 0 ); r = engine->RegisterObjectMethod("mytype", "void set_array(uint, int) property", asFUNCTION(MyStruct_set_array), asCALL_CDECL_OBJLAST); assert( r >= 0 ); ``` -------------------------------- ### Script Setting a Callback Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_callbacks.html Example of how a script can inform the application about which function to use as a callback. The script function's signature must match the registered funcdef. ```angelscript void main() { // Tell the application what script function to call SetCallback(MyCallback); } // The signature matches the registered CallbackFunc funcdef void MyCallback() { ... ``` -------------------------------- ### Initialize and Use Dictionary Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_datatypes_dictionary.html Demonstrates initializing a dictionary with key-value pairs and accessing/modifying values using get, set, and delete methods. Ensure dictionary support is registered by the application. ```AngelScript obj object; obj @handle; // Initialize with a list dictionary dict = {{'one', 1}, {'object', object}, {'handle', @handle}}; // Examine and access the values through get or set methods ... if( dict.exists('one') ) { // get returns true if the stored type is compatible with the requested type bool isValid = dict.get('handle', @handle); if( isValid ) { dict.delete('object'); dict.set('value', 1); } } ``` -------------------------------- ### Example of using GetAddressOfReturnLocation with placement new Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_generic.html Demonstrates how to use placement new with GetAddressOfReturnLocation to initialize a return value, particularly for complex types like std::string. ```c++ new(gen->GetAddressOfReturnLocation()) std::string(myRetValue); ``` -------------------------------- ### Class Property Accessor Declaration Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_class_prop.html Declare a virtual property with custom get and set logic within a class. The 'get' accessor can be marked 'const'. ```angelscript 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; } ``` -------------------------------- ### Registering List Factory Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_reg_basicref.html Demonstrates how to register a list factory for object initialization using different list patterns. ```APIDOC ## Registering List Factory This section shows how to register a list factory for object initialization with various list patterns. ### Example 1: Integer Array ```angelscript // The array type can be initialized for example with: intarray a = {1,2,3}; engine->RegisterObjectBehaviour("intarray", asBEHAVE_LIST_FACTORY, "intarray@ f(int &in) {repeat int}", ...); ``` ### Example 2: Dictionary ```angelscript // The dictionary type can be initialized with: dictionary d = {{'a',1}, {'b',2}, {'c',3}}; engine->RegisterObjectBehaviour("dictionary", asBEHAVE_LIST_FACTORY, "dictionary @f(int &in) {repeat {string, ?}}", ...); ``` ### Example 3: Grid ```angelscript // The grid type can be initialized with: grid a = {{1,2},{3,4}}; engine->RgisterObjectBehaviour("grid", asBEHAVE_LIST_FACTORY, "grid @f(int &in) {repeat {repeat_same int}}", ...); ``` ### List Pattern Tokens: - `{}`: Declares a list or sublist of values. - `repeat`: Indicates the next type or sublist can be repeated 0 or more times. - `repeat_same`: Similar to `repeat`, but ensures each repetition has the same length. - `?`: Represents a variable type where the typeId will be provided in the buffer. ### Buffer Population Rules: - `repeat`: A 32-bit integer indicating the number of repeated values. - `?`: A 32-bit integer representing the typeId of the following value. - Reference types: A pointer to the object. - Value types: The object itself. - All values are aligned to a 32-bit boundary unless smaller. ``` -------------------------------- ### Example: Struct with only floats Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html For C++ structs containing only float members, use the `asOBJ_APP_CLASS_ALLFLOATS` flag. This example demonstrates struct 'C' with three float members. ```c++ struct C { float x,y,z; }; ``` -------------------------------- ### AngelScript Comment Token Definition Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc__script__bnf_8h_source.html Defines a single token for single-line comments starting with '//' and ending with a newline, or multi-line comments starting with '/*' and ending with '*/'. ```bnf 1') // single token: starts with // and ends with new line or starts with /* and ends with */ ``` -------------------------------- ### asPrepareMultithread Source: https://www.angelcode.com/angelscript/sdk/docs/manual/group__api__multithread__functions.html Sets up the internally shared resources for multithreading. Call this from the main thread to set up shared resources if engines are to be created in multiple threads. ```APIDOC ## asPrepareMultithread() ### Description Sets up the internally shared resources for multithreading. Call this from the main thread to set up shared resources if engines are to be created in multiple threads. ### Method AS_API int asPrepareMultithread(asIThreadManager *externalMgr = 0) ### Parameters #### Path Parameters - **externalMgr** (asIThreadManager *) - Optional - Pre-existent thread manager ### Return Values - **0** on success - **asINVALID_ARG** if externalMgr is informed even though a local manager already exists - **Negative value** on error ``` -------------------------------- ### Example: Struct with only doubles Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html When a C++ struct contains only double members, use both `asOBJ_APP_CLASS_ALLFLOATS` and `asOBJ_APP_CLASS_ALIGN8` flags. This example shows struct 'D' with two double members. ```c++ struct D { double x,y; }; ``` -------------------------------- ### Example: Struct with only non-float primitives Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html If a C++ struct contains only non-float primitive types, use the `asOBJ_APP_CLASS_ALLINTS` flag. This example shows struct 'B' with an int and a void pointer. ```c++ struct B { int a; void *b; }; ``` -------------------------------- ### Example: Struct with union of floats Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html If a C++ struct contains unions of floats, use the `asOBJ_APP_CLASS_ALLFLOATS` and `asOBJ_APP_CLASS_UNION` flags. This example shows struct 'E' with two unions, each containing floats. ```c++ struct E { union { float x, s; }; union { float y, t; }; }; ``` -------------------------------- ### Type and Variable Initialization Instructions Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h.html Instructions for pushing type IDs and initializing variables with specific data types. ```APIDOC ## asBC_TYPEID ### Description Push the type id onto the stack. Equivalent to PshC4. ### Method N/A (Bytecode Instruction) ### Endpoint N/A ## asBC_SetV4 ### Description Initialize the variable with a DWORD. ### Method N/A (Bytecode Instruction) ### Endpoint N/A ## asBC_SetV8 ### Description Initialize the variable with a QWORD. ### Method N/A (Bytecode Instruction) ### Endpoint N/A ``` -------------------------------- ### StartDeserialization Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_context-members.html Initiates the deserialization process for the script context. ```APIDOC ## StartDeserialization ### Description Initiates the deserialization process for the script context. This is used to restore the state of a context from a serialized format. ### Method `StartDeserialization()` ``` -------------------------------- ### Example: Struct with additional constructors Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_val_type.html When a C++ struct has constructors beyond the default and copy constructors, use the `asOBJ_APP_CLASS_MORE_CONSTRUCTORS` flag. This example shows a struct 'A' with a constructor taking two floats. ```c++ struct A { A() = default; A(const A& o) = default; A(float x, float y) { this->x = x; this->y = y; } }; ``` -------------------------------- ### Get Address of Return Location - AngelScript Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_generic.html Gets the memory address where the return value should be placed. Use placement new for complex types to ensure proper initialization, as the memory is uninitialized. ```c++ virtual void * GetAddressOfReturnLocation ()=0 ``` -------------------------------- ### getInput Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_system.html Gets a line from the standard input. ```APIDOC ## getInput ### Description Gets a line from the standard input. ### Signature **string getInput()** ``` -------------------------------- ### Registering Global Functions Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_func.html Demonstrates how to register global functions, including those with overloads, using asFUNCTION and asFUNCTIONPR macros. ```APIDOC ## Registering Global Functions ### Description Register a global function or overloaded global functions with the AngelScript engine. ### Method `engine->RegisterGlobalFunction(signature, asFUNCTION(function_ptr), call_convention)` `engine->RegisterGlobalFunction(signature, asFUNCTIONPR(function_name, parameter_list, return_type), call_convention)` ### Parameters - **signature** (string) - The function signature as it will be known in the script. - **asFUNCTION(function_ptr)** - Macro to get the pointer for a non-overloaded global function. - **asFUNCTIONPR(function_name, parameter_list, return_type)** - Macro to get the pointer for an overloaded global function, specifying the exact function to use. - **call_convention** (enum) - The calling convention for the function (e.g., `asCALL_CDECL`). ### Request Example ```angelscript // Global function void globalFunc(); r = engine->RegisterGlobalFunction("void globalFunc()", asFUNCTION(globalFunc), asCALL_CDECL); // Overloaded global functions void globalFunc2(int); void globalFunc2(float); r = engine->RegisterGlobalFunction("void globalFunc2(int)", asFUNCTIONPR(globalFunc2, (int), void), asCALL_CDECL); ``` ### Response - **r** (int) - Return value indicating success or failure of the registration. ``` -------------------------------- ### asIScriptModule::GetName Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Gets the name of the script module. ```APIDOC ## GetName ### Description Gets the name of the module. ### Signature virtual const char * GetName() const =0 ``` -------------------------------- ### BeginConfigGroup() Source: https://www.angelcode.com/angelscript/sdk/docs/manual/functions_b.html Begins a configuration group in the AngelScript engine. ```APIDOC ## BeginConfigGroup() ### Description Begins a configuration group in the AngelScript engine. ### Class asIScriptEngine ``` -------------------------------- ### asIScriptModule::GetImportedFunctionIndexByDecl Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Gets the index of an imported function by its declaration. ```APIDOC ## GetImportedFunctionIndexByDecl ### Description Returns the imported function index by declaration. ### Signature virtual int GetImportedFunctionIndexByDecl(const char *decl) const =0 ``` -------------------------------- ### getCommandLineArgs Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_system.html Gets the command line arguments as an array of strings. ```APIDOC ## getCommandLineArgs ### Description Gets the command line arguments as an array. ### Signature **array @getCommandLineArgs()** ``` -------------------------------- ### Using CScriptHandle in C++ Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_handle.html Illustrates how to use the CScriptHandle in C++ code, including registering it as a global property and function, and how to set and retrieve object pointers. ```APIDOC ## Using CScriptHandle in C++ Even though the CScriptHandle is a value type, when registering properties of its type they should be registered as handles. The same goes for function arguments and return types. ```cpp CScriptHandle g_handle; void Function(CScriptHandle handle) { // ... use the methods of CScriptHandle to determine the true object held in it } void Register(asIScriptEngine *engine) { int r; r = engine->RegisterGlobalProperty("ref @g_handle", &g_handle); assert( r >= 0 ); r = engine->RegisterGlobalFunction("void Function(ref @)", asFUNCTION(Function), asCALL_CDECL); assert( r >= 0 ); } // To set an object pointer in the handle from the application, you'll use the Set() method // passing a pointer to the object and the type of the object. // To retrieve an object pointer from the application you'll use the Cast() method // passing in a pointer to the pointer and the wanted type id. If the type id given doesn't match // the stored handle the returned pointer will be null. // To retrieve an object of an unknown type use the GetType() or GetTypeId() to determine the type stored in the handle, // then use the Cast() method. ``` ``` -------------------------------- ### Prepare for Multithreading Source: https://www.angelcode.com/angelscript/sdk/docs/manual/group__api__multithread__functions.html Call this function from the main thread to set up shared resources for multithreading. It can optionally take a pre-existent thread manager. ```c++ AS_API int asPrepareMultithread (asIThreadManager *externalMgr=0) ``` -------------------------------- ### GetWeakRefFlagOfScriptObject Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_engine-members.html Gets the weak reference flag of a script object. ```APIDOC ## GetWeakRefFlagOfScriptObject ### Description Gets the weak reference flag of a script object. ### Method `int GetWeakRefFlagOfScriptObject(void *obj, const asITypeInfo *type) const` ### Parameters * **obj** (void *) - The script object. * **type** (asITypeInfo *) - The type information of the script object. ``` -------------------------------- ### Implementing Indexed Property Accessors Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_class_prop.html Define global indexed get and set accessors for properties that behave like array elements. The get accessor takes an index, and the set accessor takes an index and a value. Ensure compound assignments are not used with indexed properties. ```angelscript 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"); } ``` -------------------------------- ### GetSize Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_type_info.html Gets the size in bytes required to store instances of this type. ```APIDOC ## GetSize() ### Description Returns the number of bytes necessary to store instances of this type. Application registered reference types do not store this information as the script engine does not allocate memory for them. ### Method virtual asUINT asITypeInfo::GetSize() const ### Returns asUINT - The number of bytes necessary to store instances of this type. ``` -------------------------------- ### Registering Class Methods Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_register_func.html Shows how to register class methods, including overloaded and const methods, using asMETHOD and asMETHODPR macros. ```APIDOC ## Registering Class Methods ### Description Register class methods, including overloaded and const methods, to be callable from scripts. ### Method `engine->RegisterObjectMethod(object_type, signature, asMETHOD(class_name, method_name), call_convention)` `engine->RegisterObjectMethod(object_type, signature, asMETHODPR(class_name, method_name, parameter_list, return_type), call_convention)` ### Parameters - **object_type** (string) - The name of the object type in the script. - **signature** (string) - The method signature as it will be known in the script. - **asMETHOD(class_name, method_name)** - Macro to get the pointer for a non-overloaded class method. - **asMETHODPR(class_name, method_name, parameter_list, return_type)** - Macro to get the pointer for an overloaded or specific class method. - **call_convention** (enum) - The calling convention for the method (e.g., `asCALL_THISCALL`). ### Request Example ```angelscript // Class method r = engine->RegisterObjectMethod("object", "void method()", asMETHOD(Object, method), asCALL_THISCALL); // Overloaded methods r = engine->RegisterObjectMethod("object", "void method2(int)", asMETHODPR(Object, method2, (int), void), asCALL_THISCALL); r = engine->RegisterObjectMethod("object", "void method2(int, int &out)", asMETHODPR(Object, method2, (int, int&), void), asCALL_THISCALL); // Const method r = engine->RegisterObjectMethod("object", "int getAttr(int) const", asMETHODPR(Object, getAttr, (int) const, int), asCALL_THISCALL); ``` ### Response - **r** (int) - Return value indicating success or failure of the registration. ``` -------------------------------- ### GetVarCount() Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_function.html Gets the total number of local variables in the script function. ```APIDOC ## GetVarCount() ### Description Returns the number of local variables declared in the script function. ### Method `virtual asUINT GetVarCount() const` ### Returns The number of local variables in the function. ``` -------------------------------- ### Compiling a Script Module Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_compile_script.html This code demonstrates the basic steps to compile a script module. It involves creating a module, loading script content, adding it as a section, and then building the module. Error handling for the build process is included. ```cpp // Create a new script module asIScriptModule *mod = engine->GetModule("module", asGM_ALWAYS_CREATE); // Load and add the script sections to the module string script; LoadScriptFile("script.as", script); mod->AddScriptSection("script.as", script.c_str()); // Build the module int r = mod->Build(); if( r < 0 ) { // The build failed. The message stream will have received // compiler errors that shows what needs to be fixed } ``` -------------------------------- ### Get Global Property Index Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Returns the index of a global property by its name. ```APIDOC ## GetGlobalPropertyIndexByName ### Description Returns the index of the property. ### Method `virtual int GetGlobalPropertyIndexByName(const char *name) const =0` ### Parameters - **name** (const char *) - The name of the global property. ``` -------------------------------- ### Getting the Active Context Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_adv_inheritappclass.html Retrieves the currently active script execution context. ```APIDOC ## asGetActiveContext ### Description Returns the currently active script execution context. ### Function `AS_API asIScriptContext * asGetActiveContext()` ``` -------------------------------- ### Script 'any' Example Usage Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_any.html Demonstrates how to use the 'any' type in scripts to store and retrieve different types of values, including variables, object handles, and objects. ```angelscript int value; obj object; obj @handle; any a,b,c; a.store(value); // store the value b.store(@handle); // store an object handle c.store(object); // store a copy of the object a.retrieve(value); // retrieve the value b.retrieve(@handle); // retrieve the object handle c.retrieve(object); // retrieve a copy of the object ``` -------------------------------- ### Buffer Access Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_array.html Get a direct pointer to the internal buffer of the CScriptArray for low-level manipulation. ```APIDOC ## Buffer Access ### Description Returns a pointer to the internal buffer of the array, allowing for direct memory manipulation. Use with caution. ### Method `void *GetBuffer()` ``` -------------------------------- ### Element Access Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_array.html Get a pointer to an element at a specific index, or set the value of an element. ```APIDOC ## Element Access and Modification ### Description Provides methods to access and modify elements within the array by index. ### Methods - `void *At(asUINT index)` - `const void *At(asUINT index) const` - `void SetValue(asUINT index, void *value)` ### Parameters - **index** (`asUINT`) - The index of the element to access or modify. - **value** (`void*`) - A pointer to the value to be copied into the element. For handle types, this should be the address of the handle. ``` -------------------------------- ### makeDir Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_filesystem.html Creates a new directory at the specified path. Returns 0 on success. ```APIDOC ## makeDir ### Description Creates a new directory. Returns 0 on success. ### Method int makeDir(const string &in) ### Parameters #### Path Parameters - **path** (string) - Required - The path for the new directory. ### Response #### Success Response (int) - **0**: On success. ``` -------------------------------- ### Get Function Bytecode - AngelScript Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Retrieves the bytecode of a script function. Used for JIT compilation. ```c++ virtual asDWORD *GetByteCode(asUINT *length = 0) = 0; ``` -------------------------------- ### Creating and Using Script-Derived Objects from C++ Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_adv_inheritappclass.html Demonstrates how to create an instance of a script class that inherits from a C++ class, from within C++ code. It shows how to access the script object through the C++ proxy and manage its lifetime. ```cpp FooScripted *CreateFooDerived(asIScriptEngine *engine) { // Create an instance of the FooDerived script class that inherits from the FooScripted C++ class asIScriptObject *obj = reinterpret_cast(engine->CreateScriptObject(mod->GetTypeInfoByName("FooDerived"))); // Get the pointer to the C++ side of the FooScripted class FooScripted *obj2 = *reinterpret_cast(obj->GetAddressOfProperty(0)); // Increase the reference count to the C++ object, as this is what will // be used to control the life time of the object from the application side obj2->AddRef(); // Release the reference to the script side obj->Release(); return obj2; } void Foo(asIScriptEngine *engine) { FooScripted *obj = CreateFooDerived(engine); // Once the object is created the application can access it normally through // the FooScripted pointer, without having to know that the implementation // is actually done in the script. // When newly created the m_value is 0 assert( obj->m_value == 0 ); // When calling the method the m_value is incremented with 1 by the script obj->CallMe(); assert( obj->m_value == 1 ); // Release the object to destroy the instance (this will also destroy the script side) obj->Release(); } ``` -------------------------------- ### Get String Length Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_string.html Returns the number of bytes in the string. Use this to determine the size of a string. ```angelscript uint len = myString.length(); ``` -------------------------------- ### Type Properties and Size Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_type_info.html Methods to get flags, size, and type ID of a script type. ```APIDOC ## GetFlags ### Description Returns the type flags. ### Method virtual asQWORD GetFlags () const =0 ## GetSize ### Description Returns the size of the object type. ### Method virtual asUINT GetSize () const =0 ## GetTypeId ### Description Returns the type id for the object type. ### Method virtual int GetTypeId () const =0 ``` -------------------------------- ### StartDeserialization Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_context.html Initiates the deserialization of a previously serialized script context. Call FinishDeserialization after this to complete the process. ```APIDOC ## StartDeserialization() ### Description Initiates the deserialization of a previously serialized script context. After deserializing, call FinishDeserialization. ### Returns A negative value to indicate an error. Possible return values include asCONTEXT_ACTIVE if the context is currently active or suspended. ### See also Serialization of contexts ``` -------------------------------- ### GetImportedFunctionSourceModule Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_module.html Gets the name of the module from which an imported function originates. This helps in identifying the source module for importing. ```APIDOC ## GetImportedFunctionSourceModule() ### Description Retrieves the name of the module where the imported function originates. ### Method virtual const char * asIScriptModule::GetImportedFunctionSourceModule(asUINT _importIndex_) ### Parameters * **_importIndex_** (asUINT) - Required - The index of the imported function. ### Returns A null-terminated string with the name of the source module, or null if not found. ``` -------------------------------- ### Prepare Source: https://www.angelcode.com/angelscript/sdk/docs/manual/classas_i_script_context.html Prepares the context for executing a specific script function by allocating necessary stack space. ```APIDOC ## Prepare() ### Description Prepares the context for the execution of a script function. This involves allocating the required stack space and reserving space for the return value and parameters. The default value for parameters and return values is 0. ### Method virtual int asIScriptContext::Prepare(asIScriptFunction * _func) ### Parameters * **_func** (asIScriptFunction *) - Required - The ID of the function or method to be executed. ### Returns * **int** - A negative value on error. Possible error codes include: * asCONTEXT_ACTIVE: The context is still active or suspended. * asNO_FUNCTION: The function pointer is null. * asINVALID_ARG: The function belongs to a different engine than the context. * asOUT_OF_MEMORY: The context ran out of memory while allocating the call stack. ``` -------------------------------- ### Build and Execute AngelScript Module Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_hello_world.html This snippet demonstrates the complete process of building an AngelScript module from files and executing a specific function within it. Ensure the script contains the 'void main()' function. Error handling is included for module creation, file loading, compilation, function finding, and execution. ```c++ CScriptBuilder builder; int r = builder.StartNewModule(engine, "MyModule"); if( r < 0 ) { // If the code fails here it is usually because there // is no more memory to allocate the module printf("Unrecoverable error while starting a new module.\n"); return; } r = builder.AddSectionFromFile("test.as"); if( r < 0 ) { // The builder wasn't able to load the file. Maybe the file // has been removed, or the wrong name was given, or some // preprocessing commands are incorrectly written. printf("Please correct the errors in the script and try again.\n"); return; } r = builder.BuildModule(); if( r < 0 ) { // An error occurred. Instruct the script writer to fix the // compilation errors that were listed in the output stream. printf("Please correct the errors in the script and try again.\n"); return; } // Find the function that is to be called. asIScriptModule *mod = engine->GetModule("MyModule"); asIScriptFunction *func = mod->GetFunctionByDecl("void main()"); if( func == 0 ) { // The function couldn't be found. Instruct the script writer // to include the expected function in the script. printf("The script must have the function 'void main()'. Please add it and try again.\n"); return; } // Create our context, prepare it, and then execute asIScriptContext *ctx = engine->CreateContext(); ctx->Prepare(func); int r = ctx->Execute(); if( r != asEXECUTION_FINISHED ) { // The execution didn't complete as expected. Determine what happened. if( r == asEXECUTION_EXCEPTION ) { // An exception occurred, let the script writer know what happened so it can be corrected. printf("An exception '%s' occurred. Please correct the code and try again.\n", ctx->GetExceptionString()); } } ``` -------------------------------- ### Configure Engine from Stream Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_helpers.html Loads an interface from a text stream and configures the engine. This allows script compilation and bytecode saving but not script execution due to missing function pointers. ```cpp int ConfigEngineFromStream(asIScriptEngine *engine, std::istream &strm, const char *nameOfStream = "config", asIStringFactory *stringFactory = 0); ``` -------------------------------- ### Example Script with Conditional Compilation Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_build.html Shows how to use #if/#endif directives for conditional programming. This allows parts of the script to be included or excluded based on definitions set by the application, useful for client/server scenarios. ```angelscript class CObject { void Process() { #if SERVER // Do some server specific processing #endif #if CLIENT // Do some client specific processing #endif // Do some common processing } } ``` -------------------------------- ### AngelScript Class Inheritance Control Examples Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_class_inheritance.html Demonstrates the usage of 'final' for classes and methods, and 'abstract' for classes that cannot be instantiated. ```angelscript // 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 {} ``` -------------------------------- ### Get User Data - AngelScript Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Retrieves user data for a script function. Used for custom data association. ```c++ virtual void *GetUserData(asPWORD type = 0) const = 0; ``` -------------------------------- ### Example Script with Metadata Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_addon_build.html Illustrates how to add metadata to script entities like classes, functions, and variables using brackets []. This metadata is stored by the builder for post-build lookup. ```angelscript [factory func = CreateOgre] class COgre { [editable] vector3 myPosition; [editable] [range [10, 100]] int myStrength; } [factory] COgre @CreateOgre() { return @COgre(); } ``` -------------------------------- ### Get JIT Function - AngelScript Source: https://www.angelcode.com/angelscript/sdk/docs/manual/angelscript_8h_source.html Retrieves the JIT compiled function for a script function. Used for JIT compilation. ```c++ virtual asJITFunction GetJITFunction() const = 0; ``` -------------------------------- ### Get Command Line Arguments Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_stdlib_system.html Retrieve all command-line arguments passed to the script as an array of strings using `getCommandLineArgs`. ```AngelScript array @args = getCommandLineArgs(); ``` -------------------------------- ### Executing a Script Function Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_call_script_func.html This snippet demonstrates the typical workflow for executing a script function: creating a context, preparing it with the function, setting arguments, executing, and retrieving the return value. ```APIDOC ## Executing a Script Function ### Description This section outlines the steps involved in executing a script function, from preparing the execution context to retrieving the result. ### Steps 1. **Prepare the context**: Obtain or create an `asIScriptContext` instance. 2. **Obtain the function**: Get a pointer to the `asIScriptFunction` you want to call. 3. **Prepare the context for execution**: Call `ctx->Prepare(func)`. 4. **Set function arguments**: Use methods like `ctx->SetArgDWord()` to set the arguments. 5. **Execute the function**: Call `ctx->Execute()`. 6. **Retrieve the return value**: If execution finished successfully, use `ctx->GetReturnDWord()` (or other appropriate methods) to get the return value. 7. **Release the context**: Call `ctx->Release()` when done. ### Code Example ```cpp // Get a script context instance. Usually you'll want to reuse a previously // created instance to avoid the overhead of allocating the instance with // each call. asIScriptContext *ctx = engine->CreateContext(); // Obtain the function from the module. This should preferrably // be cached if the same function is called multiple times. asIScriptModule *mod = engine->GetModule(module_name); asIScriptFunction *func = mod->GetFunctionByDecl(function_declaration); // Prepare() must be called to allow the context to prepare the stack ctx->Prepare(func); // Set the function arguments ctx->SetArgDWord(0, value1); // Example for the first argument // ... set other arguments as needed int r = ctx->Execute(); if( r == asEXECUTION_FINISHED ) { // The return value is only valid if the execution finished successfully asDWORD ret = ctx->GetReturnDWord(); // ... use the return value } // Release the context when you're done with it ctx->Release(); ``` ### Key Interfaces and Methods - **`asIScriptContext`**: The interface to the virtual machine. - **`CreateContext()`**: Creates a new script context. - **`Prepare(asIScriptFunction *func)`**: Prepares the context for execution of the function. - **`SetArgDWord(asUINT arg, asDWORD value)`**: Sets a 32-bit integer argument value. - **`Execute()`**: Executes the prepared function. - **`GetReturnDWord()`**: Returns the 32-bit return value. - **`Release()`**: Decreases the reference counter. - **`asIScriptFunction`**: The interface for a script function description. - **`asIScriptModule`**: The interface for a script module. - **`GetFunctionByDecl(const char *decl)`**: Returns the function by its declaration. ### Return Codes - **`asEXECUTION_FINISHED`**: The context has successfully completed the execution. - **`asEXECUTION_SUSPENDED`**: The execution was suspended. It can be resumed by calling `Execute()` again. ``` -------------------------------- ### Prepare Source: https://www.angelcode.com/angelscript/sdk/docs/manual/functions_func_p.html Prepares the context for script execution. Associated with asIScriptContext. ```APIDOC ## Prepare() : asIScriptContext ### Description Prepares the script context for execution. ### Method (Implicitly called by the engine) ### Endpoint N/A (SDK Function) ### Parameters None explicitly documented in this context. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Read-Only and Write-Only Properties Source: https://www.angelcode.com/angelscript/sdk/docs/manual/doc_script_class_prop.html Omit either the 'get' or 'set' accessor to create read-only or write-only properties, respectively. ```angelscript class MyObj { // Read-only property int readOnlyProp { get; } // Write-only property void writeOnlyProp { set; } } ```