🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Logical Operators

Logical operators are the words and, or and not, used to combine values or flip a result. In Lua they can return any kind of value, not just true or false.

And and or return values

These operators hand back one of the values they were given. The printed results are values, not just true or false.

print(5 and 6)
print(nil or "default")
print(false or 10)
print(nil and 10)

Not gives back a boolean

The word not flips a value to the opposite boolean. Even not 0 gives a boolean, and it is false because 0 is a real value.

print(not true)
print(not false)
print(not nil)
print(not 0)

Brackets group a combined pick

The part in brackets is worked out first in each line. A missing first value leads to the fallback word none.

print((nil and "found") or "none")
print(("yes" and "found") or "none")

Example

local volume = nil
local colour = "blue"
local pickedVolume = volume or 50
local pickedColour = colour or "red"
print(pickedVolume)
print(pickedColour)
print(not volume)

Key points

  • And result: and returns the first value when it is false or nil, and otherwise returns the second value.
  • Or result: or returns the first value when it is not false or nil, and otherwise returns the second value.
  • Not result: the word not always gives back a boolean, either true or false.
  • Missing values: nil or "default" gives "default", so or can stand in for a missing value.
  • Grouping: round brackets show which part of a combined pick to work out first.

In this example, the volume setting is missing, so nil or 50 picks the stand-in value 50. The colour setting holds "blue", so or keeps that first value instead of "red". The last line shows that not volume is true, because volume holds no value.

Note

Lua writes these operators as the words and, or and not, not as symbols like && or ||.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does print(false or "hello") print?