and, or, not
Many real conditions have two parts. A ticket is valid and the seat is free. The user is an admin or the file is public. Lua joins conditions with three words: and, or and not.
local hungry = true
local hasFood = false
print(hungry and hasFood)
print(hungry or hasFood)
print(not hungry)
Output:
false
true
false
and is true only when both sides are true. or is true when at least one side is true. not turns true into false and false into true.
Checking a range
The most common use of and is to check that a number is between two limits:
local answer = 50
if answer >= 1 and answer <= 100 then
print("valid")
end
Output:
valid
You must write answer on both sides of and. In math you might write 1 <= answer <= 100, but Lua does not read it that way:
local answer = 50
if 1 <= answer <= 100 then
print("valid")
end
Output:
/usr/bin/lua5.4: main.lua:2: attempt to compare boolean with number
Lua first works out 1 <= answer, which gives true. Then it tries true <= 100, and a boolean cannot be compared with a number.
and and or give back a value
and and or do not always give true or false. They give back one of their two sides. a or b gives a when a counts as true, otherwise b. a and b gives a when a counts as false, otherwise b.
This gives Lua a short way to set a default value, a value to use when nothing else was given:
local name = nil
local shown = name or "guest"
print(shown)
Output:
guest
name is nil, so or gives back "guest". If name held "Bob", shown would be "Bob".
Lua also checks the right side only when it needs to. In a and b, if a is false or nil, Lua never looks at b. You can use this to protect a check:
local score = nil
if score and score > 50 then
print("passed")
else
print("no score yet")
end
Output:
no score yet
score is nil, so Lua stops before score > 50. Without the score and part, the program stops with the error attempt to compare number with nil.
In the exercise, write one condition with and that checks a number is from 1 to 100.