Title here
Summary here
In the specified language, angelscript, an array is a numbered sequence of elements of a specific length. In typical angelscript code, arrays are much more common; they are useful in some special scenarios.
Here we create an array a
that will hold exactly 5 integers. The type of elements and length are both part of the array’s type. By default, an array is zero-valued, which for integers means zeros.
void main() {
int[] a(5);
print("emp: " + join(a, ", ") + "\n");
// We can set a value at an index using the array[index] = value syntax,
// and get a value with array[index].
a[4] = 100;
print("set: " + join(a, ", ") + "\n");
print("get: " + a[4] + "\n");
// The length of an array can be obtained using its length property.
print("len: " + a.length() + "\n");
// Use this syntax to declare and initialize an array in one line.
int[] b = {1, 2, 3, 4, 5};
print("dcl: " + join(b, ", ") + "\n");
// You can also have the compiler count the number of elements for you
b = int[] = {1, 2, 3, 4, 5};
print("dcl: " + join(b, ", ") + "\n");
// If you specify the index with : , the elements in between will be zeroed.
b = {100, 3: 400, 500};
print("idx: " + join(b, ", ") + "\n");
// Array types are one-dimensional, but you can
// compose types to build multi-dimensional data structures.
int[][] twoD(2, int[](3));
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
twoD[i][j] = i + j;
}
}
print("2d: " + formatArray(twoD) + "\n");
// You can create and initialize multi-dimensional arrays at once too.
twoD = {{1, 2, 3}, {1, 2, 3}};
print("2d: " + formatArray(twoD) + "\n");
}
string join(int[] arr, const string &in separator) {
string result = "";
for (uint i = 0; i < arr.length(); i++) {
if (i > 0) {
result += separator;
}
result += arr[i];
}
return result;
}
string formatArray(int[][] arr) {
string result = "[";
for (uint i = 0; i < arr.length(); i++) {
if (i > 0) {
result += " ";
}
result += "[" + join(arr[i], " ") + "]";
}
result += "]";
return result;
}
To run the program, put the code in an .as
file and execute it with an appropriate Angelscript runtime.
$ angelscript arrays.as
emp: 0, 0, 0, 0, 0
set: 0, 0, 0, 0, 100
get: 100
len: 5
dcl: 1, 2, 3, 4, 5
dcl: 1, 2, 3, 4, 5
idx: 100, 0, 0, 400, 500
2d: [[0 1 2] [1 2 3]]
2d: [[1 2 3] [1 2 3]]
Now that we can run and manipulate arrays, let’s learn more about the language.