[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
locally changing global variables
From: |
Jaroslav Hajek |
Subject: |
locally changing global variables |
Date: |
Mon, 10 May 2010 13:48:04 +0200 |
hi all,
Octave's global pseudo-variables are a useful tool for customizing
Octave's settings, yet they present problems when a function is
dependent on a particular state of a certain variable. A typical
instance in my work is console output magic used for progress tracking
of a lengthy task that may be delayed or even completely spoiled by
the pager. A temporary change of a particular variable can be achieved
by unwind_protect:
function progress(n)
old_pso = page_screen_output (false);
unwind_protect
for i = 1:n
printf ("\r%d", i);
pause (0.25);
endfor
printf ("\rdone.\n");
unwind_protect_cleanup
page_screen_output (old_pso);
end_unwind_protect
endfunction
this is, however, somewhat wordy and ugly, requiring the programmer to
enclose the whole function body in an unwind_protect block, and
explicitly invent the variable name for storing the old value.
What I propose is to enable calling the pseudo-variables with a
"local" option argument, requesting the variable to be restored when
the current function exits. Thus, the previous function could be
written like this:
function progress(n)
page_screen_output (false, "local");
for i = 1:n
printf ("\r%d", i);
pause (0.25);
endfor
printf ("\rdone.\n");
endfunction
this is, of course, much more readable.
An incomplete (no ChangeLogs & no docs) patch is attached. The patch
implements the cleanup action very efficiently, reusing the existing
unwind_protect frame inside the calling function. Hence, besides being
more readable, the second form should also be more efficient. Multiple
variables may be changed at any point in the function, and they will
all be restored (in the reverse order) at the very end of the
function.
Comments? Suggestions?
--
RNDr. Jaroslav Hajek, PhD
computing expert & GNU Octave developer
Aeronautical Research and Test Institute (VZLU)
Prague, Czech Republic
url: www.highegg.matfyz.cz
local_var_changes.diff
Description: Text Data