Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Static variables?



On Jun 14,  6:55am, =?iso-8859-1?Q?Johan_Sundstr=F6m?= wrote:
} Subject: Static variables?
}
} Is it possible to use c-style "static" variables in my functions, or do I
} have to stick to global ones?

The only "persistent" variable namespace is the global one.

That said, there may be a way to get the effect you want, because the
"local" namespace has dynamic scope.  Here's how:

First, rename your precmd as precmd_body.

Next, create a function precmd_setup which assigns values to the variables
you wish to make static.

Now create a new precmd which does the following:
- Declares "local" all the variables that are assigned in precmd_setup
- Executes precmd_setup (this assigns to the locals of precmd)
- Executes precmd_body (this references the locals of precmd)
- Redefines precmd_setup to assign the new values of the locals to
  the appropriate names, e.g. eval function precmd_setup \{ ... \}

Finally, be sure that none of the affected variables is declared local
in precmd_body (so it will inherit the locals from precmd).

The tricky bit is "redefines precmd_setup."  Depending on the values of
the variables in question, it may be difficult to generate on the fly a
new definition that performs the correct assignments.  Just how ugly are
the contents of the variables you're trying to preserve?

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com



Messages sorted by: Reverse Date, Date, Thread, Author