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

Determining whether a function is used in an arithmetic context



Hey there,

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,
though.

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?)

The best luck i had was giving the function a different name when used in
arithmetic context, and then checking to see if %N matches $0. However,
this only works when function_argzero is enabled, and unfortunately i think
i need that turned off, since ZSH_ARGZERO is not available in zsh <5.3.

See below for the result of my experiments. Have i missed something?

Cheers
dana

% zsh --version
zsh 5.3.1 (x86_64-apple-darwin16.6.0)

% cat /tmp/foo
myfunc() {
  (( $1 ))
  printf '  $zec %s\n'  ${zsh_eval_context:-\?}
  printf '  $ft  %s\n'  ${functrace:-\?}
  printf '  $fs  %s\n'  ${funcstack:-\?}
  printf '  $0   %s\n'  ${0:-\?}
  printf '  $_   %s\n'  ${_:-\?}
  printf '  $ZAZ %s\n'  ${ZSH_ARGZERO:-\?}
  printf '  %%N   %s\n' ${${(%):-%N}:-\?}
  printf '  %%_   %s\n' ${${(%):-%_}:-\?}
}

functions -M func 1 1 myfunc

print 'Normal context:'
myfunc 1

print 'Arithmetic substitution context:'
: $(( func(1) ))

print 'Arithmetic command context:'
(( func(1) ))

% zsh /tmp/foo
Normal context:
  $zec toplevel
  $zec shfunc
  $ft  /tmp/foo:16
  $fs  myfunc
  $0   myfunc
  $_   myfunc
  $ZAZ /tmp/foo
  %N   myfunc
  %_   ?
Arithmetic substitution context:
  $zec toplevel
  $zec shfunc
  $ft  /tmp/foo:19
  $fs  myfunc
  $0   func
  $_   func
  $ZAZ /tmp/foo
  %N   myfunc
  %_   ?
Arithmetic command context:
  $zec toplevel
  $zec shfunc
  $ft  /tmp/foo:22
  $fs  myfunc
  $0   func
  $_   func
  $ZAZ /tmp/foo
  %N   myfunc
  %_   math


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