#782·openscad

Library variables recomputed on each module call

Author: OskarLindeCreated May 6, 2014Updated Sep 28, 2026
LabelsStalled

Here is a simplified synthetic case to illustrate the problem:

_Snippet 1_

lookup_table = expensive_computation();
function f(x) = interpolate(x, using = lookup_table);

_Snippet 2_

for (i=[1:1000]) echo(f(x));

If these two snippets are placed in the same file, everything executes as expected. The expensive_computation() is performed once and the cheap interpolate call does the work as intended. Now to the problem: if we instead put Snippet 1 in its own library: lib.scad, and call it like this

use<lib.scad>
for (i=[1:1000]) echo(f(x));

the expensive_computation() call will suddenly be performed 1000 times – causing a dramatic slowdown.

While this could all be as intended (there is a fringe use-case, see below), I think it is more likely an unintended consequence of doing what was easiest – avoiding having to find a way to store the global context of each used file, instead recomputing it at each module instantiation and function call.

Fixing the issue is easy, but I've not attached a patch as there is a remote chance that the behavior is intended, and because there is also a remote chance of this breaking / changing the behavior of some existing code that could be relying on this.

Here is the most likely (although very contrived) theoretical scenario I've come up with that would change behavior by fixing this:

_lib.scad_

var = $fn * 5;
module m() circle($fn=var);

And used:

use<lib.scad>
module n() {
    $fn = 7;
    m(); // generates a circle with 35 sides
}
n(); 

The fix would make m() generate a circle with 25 sides (default $fn*5).

That behavior is a bit inconsistent, as changing use -> include already today makes the circle get 25 sides.

Is this behavior intended, and are there any more reasonable use-cases?


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.