for loop

Program Control in OpenSCAD

The first thing to know abou OpenSCAD is that it is not an “iterative” language. When OpenSCAD “loops” trhough the for statement it basically creates an object for each of the items. There is no interalation between the items or variables.

Basic Syntax

for ( variable = [start :increment:end] )

the for statement is an operator, so it will need something to operate on

Single Child Form

The single child form below will result in 10 cubes, starting in size from 1 ( for all sides ) through 10. However, only the final cube we be visible as the largest cube covers the previous nine.

for ( i = [1:1:10) 
cube( i );
Ten Cubes all with Origin at [0,0,0]

Single Child with an Action

We can add an action to make all the cubes visible by transform each subsequent cube. The following code will produce cubes of varying sizes, that are also moved placed on the axis by the value of i

for ( i = [1:1:10) 
translate([i,0,0])
cube(i);
Ten Cubes with Origin translated by [i,0,0]

Operating on Multiple Children

A single operation can work on multiple actions and children. This code creates two sets of 10 cubes. On set growing and moving in the positive X axis, the other set in the negative X Axis.

for ( i = [1:1:10]) {
translate([i,0,])
cube(i);
translate([-i-i,0,0])
cube(i);
}

Note: Because cubes are always drawn in the XYZ Positive direction, this code subtracts the dimension of the cube in order to move it the correct amount in the negative direction.
Twenty Cubes with Origin transalted by i, and -i * 2

The for loop is powerful and can contain multiple actions, objects and other operations.

%d bloggers like this: