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

Re: Determining whether a function is used in an arithmetic context



On Mon, Jul 24, 2017 at 8:47 PM, dana <dana@xxxxxxx> wrote:
>
> I was playing with arithmetic functions recently and i wanted to have one
> of them behave differently depending on whether it's used in an arithmetic
> context or not. I can't seem to figure out a *reliable* way to detect that

I guess I'd do it like this:

myfunc() {
  if [[ ${funcstack[2]} == myfunc_math ]]
  then print In math context
  else print Not in math context
  fi
}
myfunc_math() {
  myfunc "$@"
}

functions -M myfunc 1 1 myfunc_math

> The %_ prompt expansion seemed like it might be the way to go — it produces
> math when used in an arithmetic command... but not an arithmetic
> *substitution*, strangely. (Is that expected?)

Yes, it's expected, because it's the parser state -- by the time the function is
actually executing, the parser is done.  %_ is only meaningful during program
input (typically interactively) or in an execution trace, not during
execution itself.
I think it's accidental that it has a value during arithmetic commands.



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