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

Re: easy calling of associative array?



On Nov 2,  3:01pm, Ray Andrews wrote:
} Subject: Re: easy calling of associative array?
}
} On 11/02/2015 01:05 PM, Bart Schaefer wrote:
} >
} >      typeset -g ary[idx]=val
} >
} > Ordinarly "typeset" inside a function body behaves like "local".  The
} > -g option tells it not to do that, so that the name "ary" is taken to
} > come from the calling context instead of the current function context.
} 
} I don't understand. The idea of context here is new to me. Why is
} 'ary' not a variable like any other?

Parameters have dynamic scope from the function call (not the function
name) where they are declared.  So if you have a function "upper" that
calls a function "middle" that calls a function "lower", a parameter that
is declared in "middle" is visible to "lower" but not to "upper", and a
parameter declared in "upper" is visible to both "middle" and "lower".

"typeset" is the generic "declare a parameter" builtin.  All of the other
builtins (delcare, local, integer, etc.) are special cases of "typeset".

So if both "upper" and "middle" contain "typeset -A ary", the name "ary"
in "middle" is now a new variable, not the same as the "ary" in "upper".
This is exactly like saying "local ary" in "middle", becuse "local" is
really a form of "typeset", merely given another name to make it more
obvious what's happening.

Using "typeset -gA ary" in "middle" prevents this; it says "don't declare
a new local parameter, use the one that is already in scope."

The usage with "-g ary[idx]" says "don't attempt to index into a new local
parameter $ary, instead index into the existing $ary if there is one." 
Which is what you want if the name "ary" has been passed down through $1.



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