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:

m = [];

Set key/value pairs using a syntax similar to array indexing.

m["k1"] = 7;
m["k2"] = 13;

Printing a map will show all of its key/value pairs. In OpenSCAD, we use echo for printing.

echo("map:", m);

Get a value for a key with name[key].

v1 = m["k1"];
echo("v1:", v1);

If the key doesn’t exist, the zero value of the value type is returned. In OpenSCAD, this defaults to undef.

v3 = m["k3"];
echo("v3:", v3);

The len function returns the number of key/value pairs when called on a map.

echo("len:", len(m));

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.

m["k2"] = undef;
echo("map:", m);

To remove all key/value pairs from a map:

m = [];  // Re-initialize the map
echo("map:", m);

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 "".

prs = "k2" in m;
echo("prs:", prs);

You can also declare and initialize a new map in the same line with this syntax.

n = ["foo": 1, "bar": 2];
echo("map:", n);

Note that maps appear in the form ["k":v] when printed with echo.

$ openscad -o output file.scad

The output from running the script will show the map details based on the echo statements in the code.