Maps in OpenSCAD
Maps are the target language’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the built-in make
:
Set key/value pairs using a syntax similar to array indexing.
Printing a map will show all of its key/value pairs. In OpenSCAD, we use echo
for printing.
Get a value for a key with name[key]
.
If the key doesn’t exist, the zero value of the value type is returned. In OpenSCAD, this defaults to undef
.
The len
function returns the number of key/value pairs when called on a map.
The built-in delete
removes key/value pairs from a map. In OpenSCAD, we need to implement this functionality manually since the language lacks built-in delete operators for maps.
To remove all key/value pairs from a 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 ""
.
You can also declare and initialize a new map in the same line with this syntax.
Note that maps appear in the form ["k":v]
when printed with echo
.
The output from running the script will show the map details based on the echo
statements in the code.