In what order do the statements go without brackets?

I know the title sounds confusing but let me show what i mean:

local function f(variable)
 return not variable or 1 and 3
end

My question is how does the script read this? does it return the equivalent not (variable or 1 and 3) or (not variable) or (1 and 3) or (not variable or 1) and 3?

Im not asking for the outcome of that specific order of statements, Im asking which ones go first in any order

I hope the question is understandable since i really dont know how to clearly explain it

1 Like

The operators are evaluated in this order: not first, then and, then or

So return not variable or 1 and 3 is read as: (not variable) or (1 and 3)

Think of it like math, just like multiplication comes before addition, not and and come before or

  • If variable is false/nil → not variable is true → returns true
  • If variable is true → not variable is false → returns 3 (from 1 and 3)

Quick tip: Always use parentheses when mixing logical operators to make your code clear: (not variable) or (1 and 3)

The precedence order is: notandor (highest to lowest)

3 Likes

Also, the x and y or z pattern is obsolete in Luau. In Luau, you can do if x then y else z. It’s more readable!

2 Likes

Do note, there is a very slight behavorial difference between the standard Lua idiom (which roughly simulates ternary operators), and Luau’s if-then-else expressions.


Lua idiom:

local a = true
local b = false
local c = "bar"

local foo = a and b or c
print(foo) --> "bar"

This may return an unexpected result if b evaluates to false, as it would then return c instead of b.
Whereas, the Luau expression is more explicit:

local a = true
local b = false
local c = "bar"

local foo = if a then b else c
print(foo) --> false

In most cases, the if-then-else expression is preferred, but sometimes the ‘fallback’ behavior is desired, or it might actually make your code easier to read for simpler expressions as it’s less boilerplate.

2 Likes

a or c would be a proper ternary shorthand to behave as the if statement

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.