Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Could someone clarify how math functions work?
Your second example is identical to the first so you apparently did what I
often do: forgot to make a copy of the desired text. That is, your second
example should be
zsh -c 'add() { for arg; do (( n += arg )); done; print n: $n }; functions
-M add; print results: $(( add(3,1,2) ))'
I would argue that your explanation, while correct, illustrates my point.
Namely, that the subtleties involving the parsing, execution,
interpolation, lather, rinse, repeat sequence of any Bourne shell
derivative is inherently problematic.
On Thu, Dec 18, 2014 at 9:34 PM, Bart Schaefer <schaefer@xxxxxxxxxxxxxxxx>
wrote:
>
> On Dec 18, 10:45pm, Eric Cook wrote:
> } Subject: Could someone clarify how math functions work?
> }
> } zsh -c 'add() ( for arg; do (( n += arg )); done; print n: $n );
> } functions -M add; print results: $(( add(1,2,3) ))'
> }
> } Outputs:
> } n: 6
> } results: 3
> }
> } where as:
> } zsh -c 'add() { local arg n; for arg; do (( n += arg )); done; print n:
> } $n }; functions -M add; print results: $(( add(1,2,3) ))'
> }
> } Outputs:
> } n: 6
> } results: 6
> }
> } Is that expected behavior? If so, could you explain why?
>
> The following might illustrate:
>
> zsh -c 'add() ( for arg; do (( n += arg )); done; print n: $n );
> functions -M add; print results: $(( add(3,2,1) ))'
>
> zsh -c 'add() ( for arg; do (( n += arg )); done; print n: $n );
> functions -M add; print results: $(( add(3,1,2) ))'
>
>
> When you define add() with parens ( ) around the function body, you
> are running the function body in a subshell. The "last arithmetical
> expression evaluated" IN THE CURRENT SHELL is the processing of the
> argument list of the call to add(), which is done left-to-right and
> is therefore "3" in the original example.
>
> When you define add() with braces { } you are running the function
> body in in the current shell, so the last expression is the last
> assignment in the for-loop body.
>
--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank
Messages sorted by:
Reverse Date,
Date,
Thread,
Author