From 19d451f28711bb2af75e410764a366c536de9e0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Del=20Pino?= <stephane.delpino44@gmail.com> Date: Mon, 23 May 2022 18:20:08 +0200 Subject: [PATCH] Add block description and variable lifetime explanation --- doc/userdoc.org | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/doc/userdoc.org b/doc/userdoc.org index 457d7ed44..d356b4df2 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~, -- GitLab