Contents
- Learning Objectives
- Understanding For Loops in OpenSCAD
- Using For Loops for Object Replication
- Practice Exercises
- Review
- Resources
Learning Objectives
At the end of this lesson, you will be able to:
- Understand the concept and use of for loops in OpenSCAD.
- Use for loops to repeat a block of code multiple times.
- Create objects and replicate them using for loops.
Understanding For Loops in OpenSCAD
For loops in OpenSCAD allow you to execute a block of code multiple times. The basic syntax for a for loop is:
for(variable = [start : increment : end]){
//your code here...
}
In this syntax, the variable
is the loop counter. It begins with the start
value, and each time the loop runs, it increments by the increment
amount until it reaches or exceeds the end
value. The vector [start : increment : end]
is called the loop range.
For example, the following code block executes 11 times:
for (i = [0:1:10]){
//do something(s)
}
Using For Loops for Object Replication
You can use for loops to create multiple instances of an object. For example, you can create a line of 11 evenly spaced cubes:
for (i = [0:10:100]){
translate([i,0,0])
cube(5);
}
In this example, the variable i
increments by 10 for each iteration, meaning each cube is placed 10 units apart.
You can also nest for loops (place one inside the other) to create more complex structures, like an 11x11 grid of cubes:
for (x = [0:10:100]){
for (y = [0:10:100]){
translate([x,y,0])
cube(5);
}
}
Practice Exercises
Now, it’s your turn to experiment with for loops. Try the following exercises:
- Create an 11x1 grid of evenly spaced cylinders:
for (x = [0:10:100]){
translate([x,0,0])
cylinder(h = 10, d = 10/2);
}
- Design a 10x1 grid of evenly spaced spheres:
for (x = [0:10:90]){
translate([x,0,0])
sphere(d = 10/2);
}
- Make a 10x10x10 cube of evenly spaced spheres:
for (x = [0:10:90]){
for (y = [0:10:90]){
for (z = [0:10:90]){
translate([x,y,z])
cube(5);
}
}
}
BONUS: Create a 5x5 grid of evenly spaced half-spheres:
for (x = [0:10:40]){
for (y = [0:10:40]){
translate([
x,y,0])
difference(){
sphere(d=5);
translate([0,0,2.5])
cube(5,center=true);
}
}
}
Review
In this lesson you learned:
- What a for loop is in OpenSCAD.
- How to use a for loop to repeat a block of code.
- How to use for loops to create and replicate objects.