12. Arrays

An array groups values of the same type and lets you select them by number. Creating your own arrays unlocks with Ancient research.

Group three values

int[] targets = new int[3]; creates space for three integers. int[] is the integer array type. new int[3] creates a new array of three values, initially all 0.

Each value is an element. Its position number is an index. Indices start at 0.

IndexPositionValue in this example
0First10
1Second20
2Third30

targets[0] = 10; writes 10 at index 0. The index and the stored value are different things.

Read and add the values in order

ArcaneScript
public class Program : ArcaneProgram
{
    public void OnStart()
    {
        int[] targets = new int[3];
        targets[0] = 10;
        targets[1] = 20;
        targets[2] = 30;
        int total = 0;
        for (int i = 0; i < 3; i++)
        {
            total = total + targets[i];
        }
        if (total == 60)
        {
            Workshop.Log.Write("Total is sixty.");
        }
    }
}

As i takes the values 0, 1 and 2, targets[i] reads 10, 20 and 30. total becomes 10, then 30, then 60. The autonomous spell displays Total is sixty. i selects the position and targets[i] reads the value there.

An array of three elements has indices 0 through 2. Changing the condition to i <= 3 would try to read the nonexistent index 3 and cause an error.

Array size

ArcaneScript arrays have a fixed size of 1 to 64 elements. You cannot grow an existing array. Workshop.Golems[0] reads a list provided by the game, so it works before custom arrays unlock.

Exercise

Change the last element from 30 to 40. What is the new total, and how should the if condition and message change?

Show example solutionHide example solution

Use targets[2] = 40;. The total is 10 + 20 + 40, or 70. Change the condition to total == 70 and the message to Total is seventy. The array still has three elements, so keep the for condition.