What is Lua's default behavior when you combine ands and ors in a statement?

E.g., how would Lua handle a statement like this?

if playerLikesApples and playerLikesOranges or playerLikesCherries then
     -- do something
end

Would it be treated like this:

if (playerLikesApples and playerLikesOranges) or (playerLikesCherries) then
     -- The player must like apples and oranges for the statement to execute, or they can like cherries.
end

Or like this:

if (playerLikesApples) and (playerLikesOranges or playerLikesCherries) then
     -- The player must like apples, and the player can like either oranges or cherries for the statement to execute.
end

Can this behavior be forced with parentheses?

Lua’s own website answers all of your questions. Programming in Lua : 3.5

To answer your questions:

  1. Yes. a and b or c is treated as (a and b) or c
  2. Yes. Parentheses have a high priority.
1 Like

Yeah, but it would’ve taken me a 5-10 minutes to find it myself, somehow you guys always find it within 30 seconds.

Thanks!

(Also, looks like I’m not alone, their own manual says it can be a bit confusing. “you will have the same doubt when you read the code again.”)

I highly recommend using parentheses if doing this anyway to avoid confusion for you and others.

2 Likes

They are encouraging you to actively use parentheses for logic operators. It will solve common errors as well as make your code more readable. Essentially treats it as a math equation with orders of operation; you always do the parentheses first.

1 Like