Loading

Global variables scope explanation

global variable openscad

Please Login to Comment

I know this has been covered elsewhere in terms of scoping from modules but is there an explanation somewhere as to why OpenSCAD does not really "do" global variables in the traditional sense? Was it a design decision?
ie.

A = 0;
echo("before: A=", A);
if (1)
{
A = 1;
echo("inside if block: A=", A);
}
echo("after: A=", A);

gives the output
ECHO: "before: A=", 0
ECHO: "inside if block: A=", 1
ECHO: "after: A=", 0

Great, thanks for your insightful comments everybody. And crikey, who would have thought to have read the manual!

I'll admit I have some extra insight to how OpenSCAD works that isn't covered in the manual.

I started working on a OpenSCAD-compatible compiler in JavaScript so I had to write a lot various tests involving scope and edge cases, so I looked deeper into the abyss than most people.

It falls out of what the OpenSCAD language means (i.e. the language semantics).

There is no "time" axis in the way the language constructs a model (there is "time" in the animate feature, but that's something different). There is scoping, that means design elements can be nested, but there's no sequencing.

When you write a series of statements, if they're at the same scope level they all have equal weight - they all happen "at the same time" as it were.

Have a look at Design->DisplayAST , and Design->Display CSG Tree to understand what OpenSCAD does with the code you write. After a little study and thought, it'll become clear.

I wasn't there, but I do believe it was an accepted consequence of being a "functional" language whose variables are assigned at compile time.

Very informative article here. Includes some coverage of two mechanisms for dealing with this odd variable scoping: conditional expressions (e.g. a = option=="big" ? 100 : 10) and recursion.

This is well documented in the OpenSCAD site.

Variables in OpenSCAD are scoped, so that your A inside the if block is a very different A from outside the if block.

Likewise, variables receive the LAST value assigned to them. A re-assignment at the bottom of a function/module change the values at the top.

Now, if you want WEIRD, try this:

a = 10;

if (true) {
a = a + 1;
echo("Inside if a= ", a);
}

The line a = a + 1 is magic.
The first a create a new local variable called a, but since a doesn't exist yet, the SECOND a refers to global scope.