Gretl Manual: Gnu Regression, Econometrics and Time-series Library | ||
---|---|---|
Prev | Chapter 11. User-defined functions | Next |
By default all variables are "global". There is a common namespace for variables, shared by the main script and any functions that it calls. Variables in the main script can be accessed and modified from within functions, and variables newly created within functions are added to the global dataset.
In some cases, however, it may be useful to create variables that are local or private to a particular function. You can do this by using the keyword my with genr. Inside a function, if I do
genr x = expression
I thereby create a global variable (or modify a global
variable if x
already exists). But if I
do
genr my x = expression
I create a new variable x
that is local
to the function, and will disappear when the function exits. If
a variable x
already exists outside of the
function, the above command will "mask" the outer
variable: the outer x
will be inaccessible
inside the function, and will not be modified by commands of the
sort genr x = … until the function
exits.
This behavior is illustrated by the sample script in the Section called Example showing scope of variables.
When a function, say fun1, calls another function, fun2, any local (my) variables from fun1 are by default inherited by the "child" function fun2. These variables can, however, be masked as described above by the creation of local variables of the same name within fun2.