title: Recursively constructing an object in OpenSCAD
body: <p>So I'm trying to build a simple stack of scaled cubes using a recursive function:</p>
  <pre><code>function stack(levels) = (
    levels &lt;= 0
    ? cube([1,1,1], center=true)
    : union() {
      cube([1,1,1], center=true);
      translate([0, 0, 0.9]) scale([1, 1, 0.9]) stack(levels - 1);
    }
  );
  
  stack(5);
  </code></pre>
  <p>Now for some reason I currently don't understand OpenSCAD tells me that I've got a syntax error in line 4, marking the editor like this:</p>
  <p><a href="https://i.stack.imgur.com/ztgbD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ztgbD.png" alt="highlighted syntax error in the mentioned code" /></a></p>
  <p>Sadly the console only yields this output:</p>
  <blockquote>
  <p>ERROR: Parser error in line 4: syntax error</p>
  <p>ERROR: Compilation failed!</p>
  </blockquote>
  <p>So it's somewhat hard for me to figure out what exactly I'm doing wrong.
  I guess there's a way to do this using <code>for</code>, but I would consider a recursive approach more readable.</p>
  <p>I'll try to do this with modules, and if that doesn't work I can resort to use <code>for</code> in combination with modules I suppose - it's more that I'd like this to work and find it very readable.</p>
  <hr />
  <p>Update: So from the <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/The_OpenSCAD_Language" rel="nofollow noreferrer">OpenSCAD User Manual</a> I get this snippet:
  <a href="https://i.stack.imgur.com/ILlyV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ILlyV.png" alt="OpenSCAD definition of modules and functions" /></a></p>
  <p>I would tend to interpret this so that it is not possible to create a recursive structure the way I imagined.</p>
  <p>Instead I could:</p>
  <ul>
  <li>Use a helper function to generate the cube parameters and compute their union afterwards.</li>
  <li>Rewrite the structure in terms of a <code>for</code> loop.</li>
  </ul>
  <p>I'm uncertain whether my conviction is correct, but the reasoning is this:</p>
  <ol>
  <li>I cannot create objects in a function because that would have an effect.</li>
  <li>I cannot use a module recursively because it doesn't return a result and possibly the way variables work in OpenSCAD would interfere with the idea.</li>
  </ol>