Pointers in UnrealScript

UnrealScript doesn’t have direct support for pointers like Go does. However, we can simulate similar behavior using object references and the out parameter modifier. Here’s an equivalent example:

class PointerExample extends Object;

// This function takes a value and doesn't modify the original
function ZeroVal(int iVal)
{
    iVal = 0;
}

// This function takes a reference and modifies the original
function ZeroRef(out int iRef)
{
    iRef = 0;
}

function Example()
{
    local int i;
    
    i = 1;
    `log("initial:" @ i);

    ZeroVal(i);
    `log("zeroval:" @ i);

    ZeroRef(i);
    `log("zeroref:" @ i);

    `log("reference:" @ self);
}

defaultproperties
{
}

In this UnrealScript example, we demonstrate the difference between passing by value and passing by reference, which is similar to the concept of pointers in other languages.

The ZeroVal function takes an integer parameter by value. When we pass i to this function, it receives a copy of i. Any changes made to this copy within the function do not affect the original i in the Example function.

The ZeroRef function, on the other hand, takes an integer parameter with the out modifier. This is similar to passing a pointer in other languages. When we pass i to this function, it receives a reference to i. Any changes made to this reference within the function will affect the original i in the Example function.

In the Example function, we create a local integer i and set it to 1. We then call ZeroVal(i), which doesn’t change the value of i in Example. Next, we call ZeroRef(i), which does change the value of i in Example.

Finally, we print the reference of self (the current object instance) to demonstrate how to get a reference to an object in UnrealScript.

To run this code, you would typically include it in an UnrealScript class file and compile it with the Unreal Engine. The output would be visible in the Unreal Engine log:

initial: 1
zeroval: 1
zeroref: 0
reference: PointerExample_0

This example shows that ZeroVal doesn’t change the i in Example, but ZeroRef does because it has a reference to the original variable. The last line prints the reference to the current object instance.

UnrealScript uses garbage collection for memory management, so you don’t need to worry about explicitly allocating or freeing memory as you might with raw pointers in languages like C or C++.