I don't need to test my programs. I have an error-correcting modem.

Multi-dimensional arrays

From Unreal Wiki, The Unreal Engine Documentation Site
Jump to: navigation, search

Multidimensional static or dynamic arrays are not possible in UnrealScript. Neither are dynamic arrays of static arrays or vice versa.

Workaround 1: Array of structs[edit]

A good substitute are arrays of structs that contain an array as the only member. Such a declaration for a 10x10 two-dimensional static array might look as follows:

var struct {
  var int Y[10];
} X[10];

You would access individual elements through an expression that first accesses an element in the outer array of structs, and from there access an element of the struct member:

X[3].Y[5] = 23;

Of course you can also use dynamic arrays for the same example:

var array<struct {
  var array<int> Y;
}> X;

However, be careful when accessing elements. Accessing a struct member of an element in a dynamic array is a read access to the array. As a result, you cannot use the simple assignment as above, unless you know the outer array is already long enough. You need to ensure the array length is sufficient first:

if (X.Length <= 3)
  X.Length = 4;
X[3].Y[5] = 23;

The inner array access is a write operation, so that array is resized as usual. This type of array is sometimes called a "jagged array", because the inner arrays usually have different lengths.

Workaround 2: Manual index arithmetics[edit]

Another way to store and access data as if it was arranged in multiple dimensions are index arithmetics on a one-dimensional array. Whether you use static or dynamic arrays doesn't matter here, as both use the same element access syntax.

To calculate the total size of the array, simply multiply the sizes of all dimensions. If you want a three-dimensional array with dimensions 5, 2 and 3, you need to declare an array of length 5 * 2 * 3 = 30. To access specific elements, you might want to use a macro or function that performs the necessary calculations:

const SIZE1 = 5;
const SIZE2 = 2;
const SIZE3 = 3;
function int CalcIndex(int index1, int index2, int index3)
  return (index1 * SIZE1 + index2) * SIZE2 + index3;

Zong: Looks like this is not going to work if we have a size const bigger than the previous one. Consider a two-dimensional array:

const SIZE1 = 10;
const SIZE2 = 15;
function int CalcIndex(int index1, int index2)
  return index1 * SIZE1 + index2;

CalcIndex() will return 24 for both indexes [1].[14] and [2].[4]. Similar thing happens for [0,1, ...4].[10,11, ...14] & [1,2, ...5].[0,1, ...4] with results of 10, 21, 32... etc. Or it can be represented like this: [x].[y] = [x+1].[y-10] for every y > 9.

Arkless: Probably because the formula is wrong. It should be:

const SIZE1 = 10;
const SIZE2 = 15;
const SIZEN = 1337;
function int CalcIndex(int index1, int index2, ..., int indexN) {
    return (...((index1 * SIZE2 + index2) * SIZE3 + index3)...) * SIZEN + indexN;

Just saying...