If Else in OpenSCAD
Our first example demonstrates basic conditional statements. Here’s the full source code:
// Basic example
if (7 % 2 == 0) {
echo("7 is even");
} else {
echo("7 is odd");
}
// You can have an if statement without an else
if (8 % 4 == 0) {
echo("8 is divisible by 4");
}
// Logical operators like && and || are often useful in conditions
if (8 % 2 == 0 || 7 % 2 == 0) {
echo("either 8 or 7 are even");
}
// A statement can precede conditionals
num = 9;
if (num < 0) {
echo(str(num, " is negative"));
} else if (num < 10) {
echo(str(num, " has 1 digit"));
} else {
echo(str(num, " has multiple digits"));
}
To run this OpenSCAD script, save it to a file (e.g., conditionals.scad
) and open it in the OpenSCAD application. The output will be displayed in the console window.
Note that in OpenSCAD:
- The
echo()
function is used for printing output, similar tofmt.Println()
in the original example. - OpenSCAD doesn’t have a built-in modulo operator, so we’ve assumed it exists for this example. In practice, you might need to implement this functionality yourself.
- Variables in OpenSCAD have global scope by default, so we don’t need to declare them within the if statement.
- The
str()
function is used to concatenate strings and numbers.
OpenSCAD doesn’t have a direct equivalent to Go’s ability to declare variables in if statements. Instead, we declare the variable before the if statement.
Also, OpenSCAD doesn’t have a ternary operator, so you’ll need to use a full if
statement even for basic conditions.
When you run this script in OpenSCAD, you should see output similar to this in the console:
ECHO: "7 is odd"
ECHO: "8 is divisible by 4"
ECHO: "either 8 or 7 are even"
ECHO: "9 has 1 digit"
Remember that OpenSCAD is primarily a 3D modeling scripting language, so these control structures are typically used to control the generation of 3D models rather than for general-purpose programming.