Struct Embedding in UnrealScript

Our first example demonstrates struct embedding in UnrealScript. While UnrealScript doesn’t have direct struct embedding like some other languages, we can achieve similar functionality using inheritance.

class Base extends Object;

var int num;

function string Describe()
{
    return "base with num=" $ string(num);
}

class Container extends Base;

var string str;

function Container Init(int n, string s)
{
    num = n;
    str = s;
    return self;
}

function string ToString()
{
    return "Container={num: " $ string(num) $ ", str: " $ str $ "}";
}

function Example()
{
    local Container co;
    local Base b;
    
    co = new class'Container'.Init(1, "some name");

    // We can access the base's fields directly on co
    `log("co=" $ co.ToString());

    // We can also access the base's fields through the parent class
    b = Base(co);
    `log("also num:" @ b.num);

    // Since Container extends Base, it inherits the Describe method
    `log("describe:" @ co.Describe());

    // In UnrealScript, all classes implicitly implement the Object interface
    // So we don't need to explicitly declare an interface for this example
    `log("describer:" @ Object(co).Describe());
}

In this UnrealScript version:

  1. We define a Base class with a num field and a Describe method.

  2. We create a Container class that extends Base, adding a str field.

  3. We use inheritance to achieve a similar effect to struct embedding. The Container class inherits all properties and methods from Base.

  4. We create an Init method for Container to initialize its fields, as UnrealScript doesn’t support constructor overloading.

  5. We demonstrate accessing fields and methods from the base class.

  6. In UnrealScript, all classes implicitly implement the Object interface, so we don’t need to explicitly declare an interface for this example.

  7. We use the log statement (represented here by the `log macro) instead of fmt.Printf or fmt.Println for output.

To run this code in Unreal Engine:

  1. Create a new UnrealScript file with this code.
  2. Compile the script in your Unreal Engine project.
  3. You can then call the Example function from other parts of your game code or through the Unreal Engine console.

This example demonstrates how UnrealScript uses inheritance to achieve functionality similar to struct embedding, allowing for a form of composition and method inheritance.