Map
The Map type represents a lookup of keys to values. While values can be any type, the keys can only be Keyable values like Numbers, Symbols or Strings.
Reading and writing
Map literals are specified between braces { },
and their values can be read using either a . or [] syntax:
let map = { abc = 123, def = 456 }
map.abc = 789 // equivalent to map[$abc] = 789
map["key1"] = 999 // strings can be used as a key
Fields can be stored in Maps as well:
pub field this.NumStrikes
map.NumStrikes = 8 // maps can store fields too, just like entities
let myNewMap = {
NumStrikes = 3, // set a field in a map literal
}
Removing keys
Use the delete keyword to remove a key from a Map:
let map = { abc = 123, def = 456 }
delete map.abc
Deleting a key returns its previous value, or undefined if the key did not exist.
let map = { abc = 123, def = 456 }
let value = delete map.abc // value is 123
let value2 = delete map.ghi // value2 is undefined
Iterating
You can iterate over each key-value pair in a Map using a for loop.
let map = { abc = 123, def = 456 }
for key, value in map {
// do something with `key` and `value`
}
If you want to only iterate over the keys, ignore the values using the _ placeholder:
let map = { abc = 123, def = 456 }
for key, _ in map {
// do something with `key`
}
If you only want to iterate over the values, use only one loop variable:
let map = { abc = 123, def = 456 }
for value in map {
// do something with `value`
}
Iteration order
If you only add to a Map and never delete anything from it, then the order of iteration will be the same as the order in which the key-value pairs were added.
Deleting a key causes the last value in the Map to be moved into the deleted key's position, and so the iteration order will no longer be guaranteed to be the same as the insertion order.
You can change the order of a map by using functions like Sort or SortByKey.
Concatenation
You can concatenate two maps using the + operator.
This creates a new map consisting of the key-value pairs of the first map followed by the key-value pairs of the second map.
Any keys that are present in both maps will have the value from the second map.
let map1 = { abc = 123, def = 456 }
let map2 = { ghi = 789 }
let map3 = map1 + map2 // map3 is { abc = 123, def = 456, ghi = 789 }
If you want to add new key-value pairs to an existing map, it is better to use the PushAll function, as it does not need to create a new map.
let map1 = { abc = 123, def = 456 }
let map2 = { ghi = 789 }
map1.PushAll(map2) // map1 is now { abc = 123, def = 456, ghi = 789 }