OpenSCAD Variable not accumulating

Viewed 98

I am fairly new to OpenSCAD and I've run into an issue that I don't understand. In the following snippet, the variable "ofs" is not accumulating from the previous value of the 'for' iteration.

slots = [5, 7, 11, 17];

ofs = 0;
for (i = slots) {
    ofs = ofs + i;
    echo (ofs);
    translate([ofs,0,0])
    cube([1, 50, 30]);
}

What I expect to see from echo (ofs) are the values:

  • 5 (0 + 5)
  • 12 (5 + 7)
  • 23 (12 + 11)
  • 30 (23 + 17)

What I'm actually seeing is just the value from the slots array:

  • 5
  • 7
  • 12
  • 23

Can someone tell me how I can the the value of ofs to accumulate through the iterations of the loop? Any help would be appreciated.

2 Answers

A very partial answer: As mentioned in the documentation,

variables are bound to expressions and keep a single value during their entire lifetime

they are like constants. So you can't use a for loop they way you think.

I do not have the answer. You will probably have to find a smart, vector-based way to prepare the your [5,7,12,13] vector. Maybe if you decribe how you construct your initial vector, I could assist with ideas. Or you can just wait for an answer from a more experienced user :)

The usual strategy is to calculate the values first before going into the geometry generation, e.g.:

slots = [5, 7, 11, 17];
ofs = [ for (o = 0, i = 0;i < len(slots);o = o + slots[i],i = i + 1) o + slots[i]];
echo(slots = slots, ofs = ofs);
for (o = ofs) translate([o,0,0]) cube([1, 50, 30]);
Related