doug-moen / openscad2

better abstraction mechanisms for OpenSCAD
Boost Software License 1.0
25 stars 3 forks source link

Definitions and Scoping #6

Closed gwadej closed 9 years ago

gwadej commented 9 years ago

In the section Lexical Scoping, the sentence "This means that definitions in the including script are not visible to the code in the script being included." confuses me a bit. The names declared in the included script are imported into the including script, right. Otherwise, I'm not sure what it would do. Then what does "the definitions are not visible" mean? I could guess, but it's not actually clear.

Are the "definitions" ever "visible" to the surrounding script and what would that mean?

doug-moen commented 9 years ago

From Definitions and Scoping

<< To preserve lexical scoping, the include operator has a new implementation in OpenSCAD2. It no longer performs a textual substitution, similar to #include in C. Instead, the referenced script is separately compiled, and then its top level definitions are imported into the scope of the including script. This means that definitions in the including script are not visible to the code in the script being included. >>

In OpenSCAD1, include <F> works by textually including the specified file F. Let's say this is done at the "top level" of a script S. Then top level definitions of S are mixed together with top level definitions from F. For example, if script S happens to define

/* return vertex list for i'th tan from the game of tangrams */
function tan(i) = ...;

for its own reasons, and script F happens to call tan, expecting to get the builtin tangent function, then F will instead get S's version of tan.

By contrast, OpenSCAD2 is lexically scoped. Script F is separately compiled and global names that it references are resolved independent of any script that happens to include it.

gwadej commented 9 years ago

Got it. In reading the text, I got including and included mixed up. Maybe an example like this should be included in the text.

doug-moen commented 9 years ago

Updated Lexical Scoping section with example.

gwadej commented 9 years ago

Perfectly clear now.