OpenSCAD User Manual/Modules

From Wikibooks, open books for an open world
Jump to: navigation, search

Defining your own module (roughly comparable to a macro or a function in other languages) is a powerful way to reuse procedures.

module hole(distance, rot, size) {
    rotate(a = rot, v = [1, 0, 0]) {
        translate([0, distance, 0]) {
            cylinder(r = size, h = 100, center = true);
        }
    }
}

In this example, passing in the parameters distance, rot, and size allow you to reuse this functionality multiple times, saving many lines of code and rendering your program much easier to read.

You can instantiate the module by passing values (or formulas) for the parameters just like a C function call:

hole(0, 90, 10);

The child nodes of the module instantiation can be accessed using the child() statement within the module:

module lineup(num, space) {
  for (i = [0 : num-1])
    translate([ space*i, 0, 0 ]) child(0);
}

lineup(5, 65) sphere(30);

If you need to make your module iterate over all children you will need to make use of the $children variable, e.g.:

module elongate() {
  for (i = [0 : $children-1])
    scale([10 , 1, 1 ]) child(i);
}

elongate() { sphere(30); cube([10,10,10]); cylinder(r=10,h=50); }
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export