Search code examples
openscad

OpenSCAD Variable not accumulating


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.


Solution

  • 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]);