diff --git a/doc/userdoc.org b/doc/userdoc.org index 457d7ed44b8869d2ec0d96a1de81dd21fd820963..d356b4df2ac60b8f592d3008746a21b8ce9eb020 100644 --- a/doc/userdoc.org +++ b/doc/userdoc.org @@ -591,6 +591,60 @@ It produces the following error #+results: invalid-compound-definition which is easy to fix. +*** Blocks and lifetime of variables<<blocks-and-life-time>> + +In pugs scripts, variables have a precise lifetime. They are defined +within scopes. The main scope is implicitly defined and sub-scopes are +enclosed between bracket pairs: ~{~ and ~}~. Following ~C++~, a variable +exits (can be used) as soon as it has been declare until the end of +the scope where it has been declared. At this point we give a few +examples. + +**** A variable cannot be used before its declaration +#+NAME: undeclare-variable +#+BEGIN_SRC pugs-error :exports both :results output + n = 3; + let n:N; +#+END_SRC +#+results: undeclare-variable + +**** A variable cannot be used after its definition scope +#+NAME: out-of-scope-variable-use +#+BEGIN_SRC pugs-error :exports both :results output + { + let n:N, n = 3; + n = n+2; + } + cout << n << "\n"; +#+END_SRC +#+results: out-of-scope-variable-use + +**** Variable name can be reused in an enclosed scope +#+NAME: nested-scope-variable-example +#+BEGIN_SRC pugs :exports both :results output + let n:N, n = 0; // global variable + { + cout << "global scope n = " << n << "\n"; + let n:N, n = 1; // scope level 1 variable + { + cout << "scope level 1 n = " << n << "\n"; + let n:N, n = 2; // scope level 2 variable + cout << "scope level 2 n = " << n << "\n"; + } + { + cout << "scope level 1 n = " << n << "\n"; + let n:N, n = 4; // scope level 2.2 variable + cout << "scope level 2.2 n = " << n << "\n"; + } + cout << "scope level 1 n = " << n << "\n"; + } + cout << "global scope n = " << n << "\n"; +#+END_SRC +#+results: nested-scope-variable-example +This example is self explanatory. Obviously such constructions are +generally a wrong idea. This kind of constructions may appear in loops +where the variables defined in blocks follow the same lifetime rules. + *** Basic types<<basic-types>> Basic types in ~pugs~ are boolean ~B~, natural integers ~N~, integers ~Z~,