static local variables

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

static local variables

Peter Bruhn-3
Hi,

is there some way to have local variables keep their values, after the
function has been ended and restarted?

I would like to have this, because I have a lot of sub-functions programmed
by different people. And I do not want to insert global variables into the
main-function whenever a sub-function is changed.

Actually the main-function is an exchange-market and the sub-functions are
artificial agents trading on the market. And these agents need something
like a memory. So people are programming agents and these agents should
work without changing the source of the main-function (market).

The best solution I see is to have a file of all global variables that is read by
the main-function and evaluated with 'eval'.

Thanks for any comments,
Peter

Reply | Threaded
Open this post in threaded view
|

static local variables

John W. Eaton-6
On 21-Mar-1997, Peter Bruhn <[hidden email]> wrote:

| is there some way to have local variables keep their values, after the
| function has been ended and restarted?

Currently, the only way to do this is by using global variables.

| I would like to have this, because I have a lot of sub-functions programmed
| by different people. And I do not want to insert global variables into the
| main-function whenever a sub-function is changed.

You don't need to declare the variables global in the main function.
For example, this function keeps track of the number of times it is
called:

  function f ()
    global f_static_ncalls;
    if (! exist ("f_static_ncalls"))
      f_static_ncalls = 0;
    endif
    ++f_static_ncalls
    ## ...
  endfunction

Using a name like FCN_static_FOO helps to avoid name clashses with
real global variables.

Also, it is necessary to use call exist() to decide when to initialize
the variable.  Writing

  global f_static_ncalls = 0;

*should* work to initialize the variable just once, but it doesn't.
This is a bug, and should eventually be fixed.

Finally, I realize that this is not really the Right Thing, so the
PROJECTS file contains the following entry:

  * Make it possible to have `static' variables inside functions that
    retain their values across calls.

Perhaps this will be added in the next release.  Maybe sooner, if
someone contributes the code.  :-)

Thanks,

jwe