Variadic Functions in UnrealScript

Here’s a function that will take an arbitrary number of ints as arguments.

class VariadicFunctions;

static function sum(int nums(a)) {
    local int i, total;

    `log("Nums: " $ nums.Length);

    total = 0;
    for (i = 0; i < nums.Length; i++) {
        total += nums[i];
    }

    `log("Total: " $ total);
}

static function main() {
    local array<int> nums;
    
    // Variadic functions can be called in the usual way with individual arguments.
    sum(1, 2);
    sum(1, 2, 3);

    // If you already have multiple args in an array, you can apply them to a variadic function in UnrealScript like this.
    nums[0] = 1;
    nums[1] = 2;
    nums[2] = 3;
    nums[3] = 4;
    sum(nums);
}

To execute the code, you can run it as part of an UnrealScript project. The log output will show the arguments passed to the variadic function and their sums.

$ ucc make
$ ucc exec packageName.VariadicFunctions.main

Log output will be:

Nums: 2
Total: 3
Nums: 3
Total: 6
Nums: 4
Total: 10

Another key aspect of functions in UnrealScript is their ability to form closures, which we’ll look at next.