Αληθείς τοπικές μεταβλητές
Prev | Chapter 7. Προχωρημένος προγραμματισμός με GEL | Next

## Αληθείς τοπικές μεταβλητές

When passing functions into other functions, the normal scoping of variables might be undesired. For example:

    k := 10;
    function r(x) = (x+k);
    function f(g,x) = (
      k := 5;
      g(x)
    );
    f(r,1)

you probably want the function `r` when passed as `g` into `f` to see `k` as 10 rather than 5, so that the code returns 11 and not 6. However, as written, the function when executed will see the `k` that is equal to 5. There are two ways to solve this. One would be to have `r` get `k` in a private dictionary using the square bracket notation section Returning Functions.

But there is another solution. Since version 1.0.7 there are true local variables. These are variables that are visible only from the current context and not from any called functions. We could define `k` as a local variable in the function `f`. To do this add a local statement as the first statement in the function (it must always be the first statement in the function). You can also make any arguments be local variables as well. That is,

    function f(g,x) = (
      local g,x,k;
      k := 5;
      g(x)
    );

Then the code will work as expected and prints out 11. Note that the local statement initializes all the referenced variables (except for function arguments) to a `null`.

If all variables are to be created as locals you can just pass an asterisk instead of a list of variables. In this case the variables will not be initialized until they are actually set. So the following definition of `f` will also work:

    function f(g,x) = (
      local *;
      k := 5;
      g(x)
    );

Είναι μια καλή πρακτική όλες οι συναρτήσεις που παίρνουν άλλες συναρτήσεις ως ορίσματα να χρησιμοποιούν τοπικές μεταβλητές. Με αυτόν το τρόπο η μεταβιβαζόμενη συνάρτηση δεν βλέπει λεπτομέρειες υλοποίησης και δεν μπερδεύεται.

Prev | Up | Next
Επιστροφή συναρτήσεων | Home | Διαδικασία έναρξης GEL