Struct Embedding in AngelScript

Our example demonstrates the concept of struct embedding to achieve seamless composition of types. Here’s the full source code translated to AngelScript.

class Base {
    int num;

    string describe() {
        return "base with num=" + num;
    }
}

class Container {
    Base base;
    string str;
}

void main() {
    // Initialize the container with a base and a string
    Container co;
    co.base.num = 1;
    co.str = "some name";

    // Accessing the base's fields directly on co
    print("co={num: " + co.base.num + ", str: " + co.str + "}\n");

    // Alternatively, spelling out the full path using the embedded type name
    print("also num: " + co.base.num + "\n");

    // Invoking the describe method from the embedded base
    print("describe: " + co.base.describe() + "\n");
}

interface Describer {
    string describe();
}

void TestDescriber() {
    // Creating a container instance
    Container co;
    co.base.num = 1;
    
    // Container now implements the Describer interface because it embeds Base
    Describer d = cast<Describer>(co.base);
    print("describer: " + d.describe() + "\n");
}

// Running the main function
void Run() {
    main();
    TestDescriber();
}

To run the translated AngelScript example:

$ angelscript -execute Run()

Explanation:

  1. Class Definition: Defines the Base class with a property num and a method describe() returning a string.
  2. Container Class: Defines a container class Container which contains an instance of Base and an additional string property str.
  3. Main Function: In the main function, we create an instance of Container, initialize its properties, and demonstrate accessing the properties directly or via the embedded type.
  4. Interface Implementation:
    • Defines an interface Describer with a method describe().
    • The TestDescriber function shows how embedding can be used to bestow interface implementations onto other classes by casting the embedded Base class to the Describer interface.
  5. Running the Code: A Run function calls the main() and TestDescriber() functions to demonstrate the full functionality.

This example illustrates the concept of embedding and method inheritance in AngelScript, showing how it can effectively compose complex types.