Range Over Built in UnrealScript

Here we are demonstrating how to iterate over built-in data structures using UnrealScript. Let’s see how to achieve similar functionality with various data structures we’ve learned.

class ExampleCode extends Object;

static function Main()
{
    local array<int> nums;
    local int sum, num, i;
    local map<string, string> kvs;
    local string key, value;
    local int index;
    local string word;
    
    // Using array to sum the numbers
    nums[0] = 2;
    nums[1] = 3;
    nums[2] = 4;

    sum = 0;
    for (i = 0; i < nums.length; ++i)
    {
        sum += nums[i];
    }
    `log("sum: " @ sum);

    // Iterating over array with index
    for (i = 0; i < nums.length; ++i)
    {
        if (nums[i] == 3)
        {
            `log("index: " @ i);
        }
    }

    // Iterating over map
    kvs.set("a", "apple");
    kvs.set("b", "banana");
    
    foreach kvs (key => value)
    {
        `log(key $ " -> " $ value);
    }
    
    // Iterating over map keys
    foreach kvs (key => value)
    {
        `log("key: " $ key);
    }
    
    // Iterating over string
    word = "go";
    foreach word (index => num)
    {
        `log(index @ " " @ num);
    }
}

To run the program, compile it using UnrealScript’s compiler and execute it.

$ ucc make
$ ucc example -exec ExampleCode.Main
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

The above example demonstrates iterating over arrays, maps, and strings using UnrealScript’s syntax. This allows us to efficiently access elements in these data structures, whether we’re summing numbers, finding specific values, iterating over key/value pairs, or traversing through strings.