Maps
The Map type represents a lookup of keys to values.
Keys can only be Keyable values like numbers, symbols, strings. Only integer numbers can be used as a key. If a floating point number is used as a key, it will be rounded to the nearest integer closest to zero.
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 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.
Each key-value pair will be returned in an array, which can be destructured:
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`
}