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

Re: Private variables not private enough? (Was: Get cursor position (Was: [bug report] prompt can erase messages written on the terminal by background processes))



On Sat, Dec 10, 2022 at 7:03 AM Philippe Altherr
<philippe.altherr@xxxxxxxxx> wrote:
>
> Case 1 to 4 show that both "typeset -g" and "print -v" are able to set a global variable independent of whether the variable already exists (case 1-2) or not (case 3-4).

This is true if the variable is not already declared local at some
enclosing scope.  Shell variables are dynamically scoped, defaulting
to global except when in the argument list of "typeset" and related
declarations.  Despite the apparent mnemonic, the only effect of -g is
to skip the current scope before selecting the enclosing dynamic
scope.

> Case 7 and 8 show that the same isn't true if the global variable doesn't already exist. I find this very counterintuitive. With truly private variables, I don't see why case 7 and 8 should exhibit a different behavior than case 3 and 4.
>> 7:v=
>> (anon): v: attempt to assign private in nested scope

Case 7 was a bug fixed by workers/49456.  Case 8 has the wrong error
message.  In zsh-5.9, both 7 and 8 produce the error

(anon): v: can't change parameter attribute

This is documented (last sentence of this paragraph):

   * Within any other function called by the declaring function, the
     private parameter does _NOT_ hide other parameters of the same
     name, so for example a global parameter of the same name is visible
     and may be assigned or unset.  This includes calls to anonymous
     functions, although that may also change in the future.  However,
     the private name may not be created outside the local scope when it
     was not previously declared.

This limitation is enforced by the internal implementation of dynamic
scoping in zsh as a stack of parameter declarations.  There's no way
to "unshift" a new element onto the stack at an enclosing scope.




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