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

Re: Refering to overlaid variable from within a function



On Sep 10,  2:13am, Phil Pennock wrote:
}
} Is there a way to refer to variables as they exist in the context of the
} caller of a function, so that you can use a name but not have to worry
} about the caller's names?

Yes, but it's sneaky.

    bar () {
        local a="this is bar's $1"
        print $a
        trap "$1+=\" and \"${(q-)a}" EXIT
    }
    foo () {
        local a="this is foo's a"
        print $a
        bar a
        print $a
    }

Now run "foo".

The EXIT trap runs in the context of the caller of the function which is
exiting.  The challenge, of course, is to construct a TRAPEXIT function
such that the local $a is expanded at the time the trap is defined but
the assignment doesn't occur until the trap runs, which may be trickier
for arrays or hashes than it is for strings.

This doesn't work in bash because exit traps don't run on function exit,
and don't go out of scope on function exit either.  I don't know whether
that scoping effect is likely to run afoul of some POSIX definition of
how traps work.  I don't have a genuine ksh to try.
 
On Sep 10,  9:41am, Peter Stephenson wrote:
}
} I don't think there is a clean way of doing this. The variable code
} is one of the parts that could do with a complete overhaul to make it
} maintainable but without breaking its current functionality, which is
} a bit like completely replacing the jam layer in a sponge cake with
} marmalade without breaking the cake.

Not to mention that the behavior of variable scoping is defined by the
shell language, and mucking with it could have all sorts of unforeseen
consequences.



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