OpenSCAD User Manual/Modules
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); }
One can specify default values for the arguments:
module house(roof="flat",paint=[1,0,0]){
color(paint)
if(roof=="flat"){
translate([0,-1,0])
cube();
} else if(roof=="pitched"){
rotate([90,0,0])
linear_extrude(height=1)
polygon(points=[[0,0],[0,1],[0.5,1.5],[1,1],[1,0]],paths=[ [0,1,2,3,4] ]);
} else if(roof=="domical"){
translate([0,-1,0])
union(){
translate([0.5,0.5,1]) sphere(r=0.5,$fn=20);
cube();
}
}
}
And then use one of the following ways to supply the arguments
union(){
house();
translate([2,0,0]) house("pitched");
translate([4,0,0]) house("domical",[0,1,0]);
translate([6,0,0]) house(roof="pitched",paint=[0,0,1]);
translate([8,0,0]) house(paint=[0,0,0],roof="pitched");
translate([10,0,0]) house(roof="domical");
translate([12,0,0]) house(paint=[0,0.5,0.5]);
}