Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of evaluation with mixed logical and relational operators?

What is Lua interpreting this poorly formed expression as?

return 1 or 2 == 3 and 4 -> 1

It's certainly not stepping through each operator from left to right:

return (1 or 2) == 3 and 4 -> false

Is it evaluating in reverse?

like image 741
Igorio Avatar asked Oct 19 '25 13:10

Igorio


1 Answers

You might be used to arithmetic operators having different precedences. For example, if we write 1 + 2 * 3 its assumed that the multiplication comes before the addition as in 1 + (2 * 3) instead of evaluating left to right as in (1 + 2) * 3. These standard math precedences are used in most programming languages. The only notable counterexamples I can think of are Smalltalk, that always evaluates left-to-right and languages that force you to be explicit about precedence (LISP and Forth).

As for the relational and boolean operators, it is customary for programming languages to extend the traditional arithmetic precedences to cover all the operators in the language. Lua's full precedence table can be found here:

http://www.lua.org/manual/5.2/manual.html#3.4.7

 or
 and
 <     >     <=    >=    ~=    ==
 ..
 +     -
 *     /     %
 not   #     - (unary)
 ^

The boolean and and or operators have the lowest precedences so 1 or 2 == 3 and 4 will be parsed as 1 or ((2 == 3) and 4).

like image 93
hugomg Avatar answered Oct 22 '25 05:10

hugomg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!