Arrays in UnrealScript

Our first example demonstrates the use of arrays in UnrealScript. In UnrealScript, an array is a collection of elements of a specific type.

class ArrayExample extends Object;

function RunExample()
{
    // Here we create an array 'a' that will hold exactly 5 integers.
    // By default, an array is initialized with default values, which for integers means 0s.
    local array<int> a;
    a.Length = 5;
    `log("emp:" @ a);

    // We can set a value at an index using the array[index] = value syntax,
    // and get a value with array[index].
    a[4] = 100;
    `log("set:" @ a);
    `log("get:" @ a[4]);

    // The Length property returns the length of an array.
    `log("len:" @ a.Length);

    // Use this syntax to declare and initialize an array in one line.
    local array<int> b;
    b = [1, 2, 3, 4, 5];
    `log("dcl:" @ b);

    // In UnrealScript, we can't directly specify the size of an array during initialization.
    // Instead, we can add elements to the array using the AddItem function.
    b.Length = 0;
    b.AddItem(100);
    b.AddItem(0);
    b.AddItem(0);
    b.AddItem(400);
    b.AddItem(500);
    `log("idx:" @ b);

    // Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.
    local array< array<int> > twoD;
    twoD.Length = 2;
    twoD[0].Length = 3;
    twoD[1].Length = 3;
    
    local int i, j;
    for (i = 0; i < 2; i++)
    {
        for (j = 0; j < 3; j++)
        {
            twoD[i][j] = i + j;
        }
    }
    `log("2d:" @ twoD);

    // You can create and initialize multi-dimensional arrays at once too.
    twoD[0] = [1, 2, 3];
    twoD[1] = [1, 2, 3];
    `log("2d:" @ twoD);
}

DefaultProperties
{
}

Note that arrays in UnrealScript are typically printed in the form (Elements=(1,2,3)) when using the @ operator for string concatenation.

To run this example, you would typically place this code in a script file (e.g., ArrayExample.uc) within your UnrealScript project, compile it, and then call the RunExample() function from elsewhere in your game code or through the UnrealScript console.

UnrealScript’s array handling is somewhat different from many other languages:

  1. Arrays are dynamic by default, meaning they can grow or shrink as needed.
  2. The Length property is used both to get the current length and to set a new length.
  3. There’s no built-in way to initialize an array with a specific size and values in one line, so we have to do it in steps.
  4. Multi-dimensional arrays are created as arrays of arrays.

This example demonstrates basic array operations in UnrealScript, including creation, initialization, accessing elements, and working with multi-dimensional arrays.