mirror of
git://git.code.sf.net/p/zsh/code
synced 2025-10-24 04:50:27 +02:00
22416: forgot zmathfuncdef
This commit is contained in:
parent
6555629356
commit
5d9563ab12
1 changed files with 45 additions and 0 deletions
45
Functions/Misc/zmathfuncdef
Normal file
45
Functions/Misc/zmathfuncdef
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
# Define a mathematical function with its definition and smart(ish)
|
||||
# guessing of the number of arguments. Doesn't overload for different
|
||||
# numbers of arguments, but that could be done. Type overloading would be
|
||||
# more fraught.
|
||||
|
||||
emulate -L zsh
|
||||
setopt extendedglob
|
||||
|
||||
if (( $# < 1 || $# > 2 )); then
|
||||
print "Usage: $0 name [body]" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local mname=$1
|
||||
local fname="zsh_math_func_$1"
|
||||
|
||||
if (( $# == 1 )); then
|
||||
functions +M $mname && unfunction $fname
|
||||
return 0
|
||||
fi
|
||||
|
||||
integer iarg=0 ioptarg
|
||||
local body=$2
|
||||
|
||||
# count compulsory arguments
|
||||
while [[ $body = *'$'$((iarg+1))(|[^[:digit:]]*) ]]; do
|
||||
(( iarg++ ))
|
||||
done
|
||||
|
||||
# count optional arguments
|
||||
(( ioptarg = iarg ))
|
||||
while [[ $body = *'${'$((ioptarg+1))':-'* ]]; do
|
||||
(( ioptarg++ ))
|
||||
done
|
||||
|
||||
functions -M $mname $iarg $ioptarg $fname || return 1
|
||||
|
||||
{
|
||||
eval "$fname() { (( $body )) }"
|
||||
} always {
|
||||
# Remove math function if shell function definition failed.
|
||||
if (( TRY_BLOCK_ERROR )); then
|
||||
functions +M $mname
|
||||
fi
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue