Array
The Array type represents a list of values. An array can contain any type of value, including other arrays. An array can be modified after it is created - elements can be added, removed or replaced.
Reading and writing
Use the []
syntax to create an array, and then the subscript []
operator to read and write elements:
let array = [123, 456, 789]
array[1] // read element 1: outputs 456
array[1] = 999 // replace element 1 with 999, array is now [123, 999, 789]
Pushing and popping elements
You can add elements to the end of an array using the Push method,
let array = [123]
array.Push(456).Push(789) // array is now [123, 456, 789]
Remove the last element from an array using the Pop method:
let array = [123, 456, 789]
let last = array.Pop() // last is 789, array is now [123, 456]
Deleting elements
Use the delete
keyword to remove an element from an array.
This replaces the value with undefined
but does not change the length of the array:
let array = [123, 456, 789]
delete array[1] // array is now [123, undefined, 789]
Deleting an element returns its previous value, or undefined
if the element did not exist:
let array = [123, 456, 789]
let value = delete array[1] // value is 456
let value2 = delete array[5] // value2 is undefined
Iterating
You can iterate over each element in an array using a for
loop:
let array = [123, 456, 789]
for value in array {
Transmission { %(value) }
}
// Outputs 123, 456, 789
You can also provide two loop variables to iterate over the index and value of an Array:
let list = ["Potato", "Tomato", "Banana"]
for index, value in list {
Transmission { %(index + ": " + value) }
}
// Outputs "0: Potato", "1: Tomato", "2: Banana"
Concatenation
You can concatenate arrays using the +
operator.
This will create a new array consisting of the elements of the first array followed by the elements of the second array:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = a + b // c is [1, 2, 3, 4, 5, 6]
If you want to add new elements to an existing array, it is better to use the PushAll functions as that does not require creating a new array:
let a = [1, 2, 3]
let b = [4, 5, 6]
a.PushAll(b) // a is now [1, 2, 3, 4, 5, 6]
Constant arrays
Some arrays are constant. That is, they are generated at compile time and cannot be changed at runtime. This can improve the performance of your game.
In particular, arrays generated using the Asset wildcard syntax are constant:
let images = @images/fireball-*.svg
let frame0 = images[0] // e.g. @fireball-0.svg
images[0] = @thunderbolt.svg // error: cannot modify a constant array