Evaluation of complex conditions

Alex Tweedly alex at tweedly.net
Thu Oct 6 06:55:30 EDT 2011


Don't confuse "operator precedence" and "order of evaluation".

precedence tells you how the results of individual parts of the 
calculation are combined. For instance,  1+2*3+4 will give 11 (i.e. 
multiplication is higher precedence than addition, so the 2 is 
multiplied by the 3 and then that is used in the lower precedence 
addition). If you wanted different, you would need brackets  ...   
(1+2)*(3+4) would give you 21 (3*7).

order of evaluation (for LC) is  left to right (regardless of precedence 
!!).

Try this cute test case
> global C
>
> function getnext
>    add 1 to C
>    return C
> end getnext
>
> on mouseUp
>    put 0 into C
>    put getnext()+getnext()*getnext()+getnext()
> end mouseUp
this results in 11 - i.e. 1 + 2*3 + 4

If evaluation order had followed precedence then it would have been 3 + 
(1*2) + 4 ---> 9

The similar rules apply when evaluating logical expressions in a test 
condition, with the additional proviso that LC will stop evaluating the 
terms of the expression as soon as the eventual result is determined. So,
> on mouseUp
>    put 0 into C
>    if getnext() > 0 and getnext() < 2 and getnext()< 3 and getnext()<3 
> then
>       put "that's a surprise"
>    else
>       put getnext()
>    end if
> end mouseUp
produces 3  (first term is true, second term is false and at that point 
we know the whole expression must be false, so we stop evaluating - 
therefore the next call to getnext() produces 3

-- Alex.

On 06/10/2011 01:26, Pete wrote:
> I just read the section in the manual about operator precedence and I think
> perhaps I'm even more confused than I was!  It details a strict order of
> precedence which seems to contradict the knowledge that condition evaluation
> proceeds from left to right and stops as soon as a false one is found.
>
> Maybe I'll try a few test cases.
>
>
> Pete
> Molly's Revenge<http://www.mollysrevenge.com>
>





More information about the use-livecode mailing list