Variables in OpenSCAD

Our first example demonstrates how to declare and use variables in OpenSCAD. Here’s the full source code:

// In OpenSCAD, variables are declared using the 'variable = value' syntax

// Declare and initialize a string variable
a = "initial";
echo(a);

// Declare multiple variables at once
b = 1;
c = 2;
echo(b, c);

// OpenSCAD will infer the type of initialized variables
d = true;
echo(d);

// Variables without initialization are undefined in OpenSCAD
e = undef;
echo(e);

// Declare and initialize a variable in one line
f = "apple";
echo(f);

In OpenSCAD, variables are declared using the variable = value syntax. Unlike some other languages, OpenSCAD doesn’t have explicit type declarations.

You can declare and initialize variables in one line. OpenSCAD will infer the type of the variable based on the assigned value.

To see the output of our variables, we use the echo() function, which prints values to the console.

OpenSCAD doesn’t have a concept of zero-valued variables. Instead, uninitialized variables are undefined.

To run this script, save it as a .scad file and open it in the OpenSCAD application. The output will be displayed in the console window:

ECHO: "initial"
ECHO: 1, 2
ECHO: true
ECHO: undef
ECHO: "apple"

Note that OpenSCAD is primarily a 3D modeling scripting language, so it doesn’t have a traditional “main” function or program entry point. The script is executed top to bottom when you open or render the file.

Now that we’ve seen how to declare and use variables in OpenSCAD, let’s explore more features of the language.