discuss@lists.openscad.org

OpenSCAD general discussion Mailing-list

View all threads

Re: IF and strings in openSCAD

JB
Jordan Brown
Mon, Mar 28, 2022 4:24 PM

The important thing to know here is that OpenSCAD does not behave like
a conventional programming language.  What look like variables in
OpenSCAD really aren't variables.  They are perhaps better thought of as
named constants - and they only last to the end of the scope that they
are created in.

So for instance:

flag = true;
v = 1;
echo(v);
if (flag) {
    v = 2;
    echo(v);
} else {
    v = 3;
    echo(v);
}
echo(v);

In a conventional programming language, that would print 1, 2, 2,
right?  In OpenSCAD, the v=2 only lasts until the end of that block, and
so what you get is:

ECHO: 1
ECHO: 2
ECHO: 1

If you want to have a "variable" have a value that depends on a
conditional, you have to use the a?b:c construct:

v = flag ? 2 : 3;
The important thing to know here is that OpenSCAD does *not* behave like a conventional programming language.  What look like variables in OpenSCAD really aren't variables.  They are perhaps better thought of as named constants - and they only last to the end of the scope that they are created in. So for instance: flag = true; v = 1; echo(v); if (flag) { v = 2; echo(v); } else { v = 3; echo(v); } echo(v); In a conventional programming language, that would print 1, 2, 2, right?  In OpenSCAD, the v=2 only lasts until the end of that block, and so what you get is: ECHO: 1 ECHO: 2 ECHO: 1 If you want to have a "variable" have a value that depends on a conditional, you have to use the a?b:c construct: v = flag ? 2 : 3;