Maps in GDScript
Maps are built-in associative data types (sometimes called hashes or dicts in other languages).
To create an empty map, use the dictionary initializer:
Set key/value pairs using typical name[key] = val
syntax.
Printing a map will show all of its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, the value type returns null
.
The built-in size()
method returns the number of key/value pairs when called on a map.
The built-in erase()
method removes key/value pairs from a map.
To remove all key/value pairs from a map, you can reinitialize the map.
The optional second return value when getting a value from a map indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or null
. Use has()
to check if a key exists.
You can also declare and initialize a new map in the same line with this syntax.
Note that dictionaries appear in the form {k: v, k: v}
when printed with print()
.