Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: local but persistent integer?
On Fri, Sep 16, 2022 at 8:19 AM Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:
>
> integer -x start="$(( $(date +%s%N)/1000000 ))"
>
> ... I need 'start' to persist between function calls which it does
Given that construct, it should not. "integer -x" within a function
puts something in the environment (so visible to external processes),
but it's still scoped to the function and goes away when the function
finishes.
> I tried 'unset' but it didn't seem to work.
That indicates that you're unsetting the local, but there must still
be another global $start that came from somewhere. Use a more
distinctive variable name (see below).
> it would be nice if it could be local as well since it has no use
> outside this function.
Unfortunately the base model for shell variables (a form of dynamic
scoping) and interpretive function invocation does not lend itself to
the form of static scoping that you're hoping for. A second run of a
function is just re-interpreting the function source code, not
re-entering any existing scope other than the global one.
Your best bet is to use something like
integer -gH _myfn_start=$((....))
(( $_myfn_start == 0 )) && ...
which will create a global variable whose value is concealed, using a
name that only your function "knows about".
This can be generalized with something like this (assumes proper
option settings to make ${0} reflect the current function name):
integer -gH _${0}_start=...
(( ${(P)${:-_${0}_start}} == 0 )) && ...
but that's probably overkill in your case.
Messages sorted by:
Reverse Date,
Date,
Thread,
Author