Pointers in OpenSCAD

OpenSCAD does not have a direct equivalent to pointers, as it is primarily a 3D modeling scripting language. However, we can demonstrate similar concepts using variables and functions.

// OpenSCAD supports variables and functions, allowing you to pass values
// and modify them within your program.

// This function attempts to set the value to 0, but it won't affect the original variable
function zeroval(val) = 0;

// This function returns a new value set to 0
function zeroptr(val) = 0;

// Main script
function main() = 
    let(i = 1)
    let(initial = echo("initial:", i))
    let(zeroval_result = zeroval(i))
    let(after_zeroval = echo("zeroval:", i))  // i remains unchanged
    let(i_new = zeroptr(i))
    let(after_zeroptr = echo("zeroptr:", i_new))  // i_new is now 0
    0;  // OpenSCAD functions need to return a value

main();

In OpenSCAD, variables are immutable, so we can’t directly modify them as we would with pointers in other languages. Instead, we create new variables with updated values.

The zeroval function attempts to set the value to 0, but it won’t affect the original variable because OpenSCAD passes arguments by value.

The zeroptr function returns a new value set to 0, which we then assign to a new variable. This is the closest we can get to simulating the behavior of pointers in OpenSCAD.

To run this script:

  1. Save the code in a file with a .scad extension (e.g., variables.scad).
  2. Open the file in the OpenSCAD application.
  3. Click on “Design” -> “Compile and Render” or press F6.

The output will be displayed in the console window:

ECHO: "initial:", 1
ECHO: "zeroval:", 1
ECHO: "zeroptr:", 0

As you can see, the zeroval function doesn’t change the original value of i, but zeroptr effectively creates a new variable with the value set to 0.

Note that OpenSCAD is primarily used for 3D modeling, so these concepts are typically applied in the context of creating and manipulating 3D objects rather than general-purpose programming.