Functions in OpenSCAD

Our first example demonstrates how to define and use functions in OpenSCAD. We’ll create two simple functions that perform arithmetic operations.

// Here's a function that takes two numbers and returns their sum
function plus(a, b) = a + b;

// This function takes three parameters and returns their sum
function plusPlus(a, b, c) = a + b + c;

// Main part of the script
function main() = {
    // Call a function as you'd expect, with name(args)
    res1 = plus(1, 2);
    echo("1+2 =", res1);

    res2 = plusPlus(1, 2, 3);
    echo("1+2+3 =", res2);
};

// Execute the main function
main();

In OpenSCAD, functions are defined using the function keyword followed by the function name and parameters. The function body is a single expression that follows the = sign.

Unlike some languages, OpenSCAD doesn’t require explicit return statements. The value of the expression is automatically returned.

To execute this script:

  1. Save the code in a file with a .scad extension, for example functions.scad.
  2. Open the file in OpenSCAD.
  3. Look at the console output to see the results of the echo statements.

You should see output similar to this:

ECHO: "1+2 =", 3
ECHO: "1+2+3 =", 6

Note that OpenSCAD doesn’t have a concept of a “main” function like some other languages. Instead, any code at the top level of the script is executed when the script is run. In this example, we’ve wrapped our main code in a function and then called it immediately, but this isn’t strictly necessary in OpenSCAD.

OpenSCAD functions are primarily used for mathematical operations and are evaluated at compile time. For more complex operations involving geometry, you would typically use modules instead of functions.