Command Line Subcommands in OpenSCAD
Here’s the translation of the Go code to OpenSCAD, with explanations in Markdown format suitable for Hugo:
Our first program will demonstrate how to create a simple 3D object and use command-line arguments in OpenSCAD. Here’s the full source code:
// Define a module for our basic shape
module basic_shape(size) {
cube(size);
}
// Main part of the script
function main() =
let(
// Parse command line arguments
args = $args,
// Default size if no argument is provided
default_size = 10,
// Get the size from arguments or use default
size = len(args) > 0 ? str(args[0]) : default_size
)
// Create and render the shape
basic_shape(size);
// Call the main function
main();In OpenSCAD, we don’t have the concept of subcommands like in the original Go example. Instead, we’ll focus on using command-line arguments to parameterize our script.
To run the script, save it as basic_shape.scad and use the OpenSCAD command-line interface:
$ openscad -o output.stl basic_shape.scadThis will create a default cube with size 10.
To specify a custom size:
$ openscad -o output.stl -D '$args=["20"]' basic_shape.scadThis will create a cube with size 20.
OpenSCAD doesn’t have built-in argument parsing like the flag package in the original example. Instead, we use the special $args variable to access command-line arguments.
In our script:
- We define a
basic_shapemodule that creates a cube of given size. - The
mainfunction parses arguments and callsbasic_shape. - We use
let()to create local variables for argument parsing. - If an argument is provided, we use it as the size; otherwise, we use a default value.
- Finally, we call the
mainfunction to execute our script.
This example demonstrates how to create a simple parameterized 3D model in OpenSCAD and how to use command-line arguments to modify the output. While it doesn’t have the same level of command-line argument handling as the original Go example, it shows how to achieve similar functionality within the constraints of the OpenSCAD language.