local a = true print(a and false or true) why result always be true whether a==false or a == true?

1394 views lua
-4

enter image description here

why not a is corrct? can't understand.

Code:

C:\Users\Administrator>lua53
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> local a = true print(a and false or true)
true
> local a = false print(a and false or true)
true
> local a = false print(a == true and false or true)
true
> local a = true print(a == true and false or true)
true
> local a = true print(a == false and false or true)
true
> local a = false print(a == false and false or true)
true
> local a = false print((a == false) and false or true)
true
> local a = false print(not a )
true
> local a = true print(not a )
false
>

answered question

Please do not post pictures of code. Or other text. Post the actual text. And the code that generated it.

local a = true print(a == true and false or true) ,and the result is true,I think it must be false. so I change the codes to be : local a = true,print(not a ),then it's correct !

Your question is still unclear. What about this do you not understand?

1 Answer

5

In Lua, and and or have the lowest operator precedence, with or being lower than and. Therefore, any expression of the form X and false or true will be interpreted as (X and false) or true.

Well, anything logically and-ed with false is false; that's how logical and works. And anything logically or-ed with true is true. And since or comes last, all of those expressions are just over-complicated ways of saying true.

posted this

Have an answer?

JD

Please login first before posting an answer.