[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: locally changing global variables
From: |
Jaroslav Hajek |
Subject: |
Re: locally changing global variables |
Date: |
Tue, 18 May 2010 08:49:20 +0200 |
On Tue, May 18, 2010 at 8:26 AM, John W. Eaton <address@hidden> wrote:
> On 18-May-2010, Jaroslav Hajek wrote:
>
> | Currently, I think not. It would be possible if we had a working
> | onCleanup implementation. Despite we have unwind_protect, which is, in
> | most practical ways, more versatile, onCleanup being an object allows
> | for doing magic, such as injecting a cleanup action to caller scope
> | (which could be the solution here). I'll start a separate thread about
> | this.
>
> Thinking about this a little more, I guess I'd like to do something
> like:
>
> function retval = my_special_value (val, opt)
> persistent curr_val = "default_value";
> make_local = nargin == 2 && strcmp (opt, "local");
> if (nargin == 1 || nargin == 2)
> if (nargin == 2)
> __make_local_variable__ (@my_special_value, curr_val);
> endif
> if (nargout > 0)
> retval = curr_val;
> endif
> curr_val = val;
> elseif (nargin == 0)
> retval = curr_val;
> else
> print_usage ();
> endif
> endfunction
>
> Is there no way to have the __make_local_variable__ function call
> above hook into your current mechanism for restoring variable values?
with onCleanup, you could do something like:
## Check for existing restore action first. If none, create it.
if (! evalin ("caller", "exist(\"__my_special_value__restore\", \"var\")"))
restore = onCleanup (@() my_special_value (curr_val));
assignin ("caller", "__my_special_value__restore", restore);
endif
and it is even Matlab compatible. It is a small snippet, though kinda
ugly. It would also be possible to create a function that would allow
adding user hooks to the unwind_protect frame (like my recent change
does), but you would still need evalin().
--
RNDr. Jaroslav Hajek, PhD
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz