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

Re: Up-scope named references, vs. ksh



2024-02-28 21:16:13 -0800, Bart Schaefer:
[...]
> That's where this whole discussion started:  It's not good enough to
> "record that it's to be global" because if a local of the same name is
> later declared, there is no way to insert a new global "above" that,
> it's akin to attempting to allocate new space in your caller's stack
> frame in C (except there's one stack for each parameter name).  The
> workaround in shell code is to start with "typeset -g a" (using your
> example code) to initialize the top stack frame.  The workaround in
> underlying C code would be to have "typeset -n r1=a" (again your
> example) implicitly create the global $a as early as possible.
[...]

Couldn't typeset -n ref=var, when it finds that var is not set
create one in global scope with a "unset-but-referenced" flag
and maybe a reference count associated with it and that can be
unset but not removed until the reference count reaches 0 when
no nameref point to it?

Another (similar) problem:

Imagine a function meant to create a variable whose name is
passed as argument *as a scalar*:

$ ./Src/zsh -c 'f() { typeset -n ref=$1; local var=2; ref=3; }; typeset -A var; f var; echo $var'
f: var: attempt to set slice of associative array

Doesn't work if the variable was previously set as a hash.

Work around would be to unset it first but:

$ ./Src/zsh -c 'f() { typeset -n ref=$1; unset ref; local var=2; ref=3; }; typeset -A var; f var; echo $var'
<empty>

$ref ended up pointing to the local var again instead of the one
in global scope it was intended to reference.

Comparing with ksh93:

$ ksh -c 'function f { typeset -n ref=$1; typeset var=2; ref=3; }; typeset -A var=([a]=b); f var; typeset -p var'
typeset -A var=([0]=3 [a]=b)
$ ksh -c 'function f { typeset -n ref=$1; unset ref; typeset var=2; ref=3; }; typeset -A var=([a]=b); f var; typeset -p var'
var=3

-- 
Stephane




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