Arrays

Overview

Arrays in BattleScript are a language feature: you declare typed arrays, write array literals and access elements by index. There are currently no built-in array helper methods — methods such as push, pop, shift, splice, indexOf, includes and filter do not exist, and there is no .length property or std::arrays library. To process an array you iterate it with a counted for loop.

Declaring arrays

Typed array declaration

Description: Declare a typed array using type[] and assign an array literal.

Syntax: type[] arrayName = [value1, value2, ...];

Example:

// An array of integers
int[] nums = [1, 2, 3];

// An array of strings
string[] playerNames = ["Player1", "Player2", "Player3"];

// A two-dimensional array of strings
string[][] grid = [["a", "b"], ["c", "d"]];

// An array of a custom interface type
Player[] players = [];

Accessing elements

Index access

Description: Read and write elements by their zero-based index.

Syntax: arrayName[index]

Example:

string[] names = ["Alice", "Bob", "Charlie"];

// Read the first element (index 0)
string firstPlayer = names[0];  // "Alice"

// Write a value at a specific index
names[1] = "Bobby";  // names is now ["Alice", "Bobby", "Charlie"]

Iterating with a for loop

Counted for loop

Description: Because there is no .length property, iterate using a known element count.

Example:

int[] scores = [85, 92, 78, 90];

// Iterate over the four known elements
for (int i = 0; i < 4; i++) {
    std::console.log("Score", i, ":", scores[i]);
}

Related Topics