for loop – OpenSCAD for loop Tutorial

Program Control in OpenSCAD

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

Official Wiki Page: for loop

Basic Syntax

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

When the for loop is evaluated the “variable” will be assigned values equal to start, then the next value of start + increment, until 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.

In the example the variable i , is replaced with the values 1,2,3,4,5,6,7,8,9,10 and a cube is created for each of the values.

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 transforming 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,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.

Coming Soon !

Three forms of the for loop

Standard Form

for ( i = [start:stop] );

Increment Form

for ( i = [start:increment:stop] );

As a list iterator

for ( i = [1,6,4,10,9,99,100] );

Using the for-loop with a rotation

If we use the variable assigned in the for loop, we can create multiples of the child object ( in this case a sphere ). It is useful to note that the “child object” is any geometry within the rotate scope. The scope is either a single geometry following the rotate modifier or multiple geometries within the brackets.

Ring of Spheres using for loop
for ( i = [1:10:360])
  rotate(i,[0,0,1]){
     translate([10,0,0]) sphere([1],$fn=25);
  }

Using the for-loop with translate

Nested for-loop