Why is it insufficient to make the body of the loop an anonymous function?
That would work but function calls are rather expensive and it feels syntactically heavy to me (2 extra lines + extra indentation). In most cases, I would probably prefer adding "unset -n ref" before the "typeset".
The main question though is whether we can turn initializations of references with empty strings into errors.
Currently, "typeset -n ref=$varname" may or may not initialize the reference even though it's extremely unlikely that anyone would write such code with the intent that an empty "varname" should indeed not initialize "ref". I wouldn't mind if only syntactically empty values would leave "ref" uninitialized (i.e., if only "typeset -n ref=" would leave "ref" uninitialized but not "typeset -n ref='""" and never "typeset -n ref=$varname"). However, I suspect that this would be very hard to implement, for the same reason as why Zsh can't support the ksh's $1 magic behavior in "typeset -n ref=$1".
Another consequence of the current treatment of empty variable names is that when TYPESET_TO_UNSET is enabled, there are two types of reference placeholders: ones with no initialization and ones initialized with an empty variable name:
$ typeset -n ref1 ref2=
$ typeset -p ref1 ref2
typeset -n ref1
typeset -n ref2=''
This stinks of bad design in my opinion. It's even more sad given the fact that otherwise everything is so nice and tidy with TYPESET_TO_UNSET enabled.
Our users would be better served and things would look better when TYPESET_TO_UNSET is enabled, if initializing references with empty strings would trigger an error (like when you initialize it with an invalid variable name). The only loss that I could identify is that the following code would no longer work:
for ... do
typeset -n ref=
...
done
Instead, you would have to write "unset -n ref; typeset -n ref" or alternatively use "typeset -n ref" and move the loop body into an anonymous function.
If both of these are deemed too heavy then we could introduce a new -S option for "typeset" that would allow writing "typeset -Sn ref". That new option would also be useful beyond references. For example, if TYPESET_TO_UNSET is enabled and you want to define an unset string at the start of a loop. You could do that with "typeset -S str" while currently you have to use one of the two tricks described before for "typeset -n ref=".
Philippe