A Boolean, or Bool for short, is a very simple data type. It is either a true or false value.
Booleans are most commonly used with conditional statements.
MyBool = true if MyBool then --If "MyBool"'s value is true, this code is run. else --If "MyBool"'s value is false, this code is run. end
In Lua, if a value not is false or nil then it is considered "truthy". When used in an if, while, or repeat statement, truthy values are treated as if they were true, and other values are treated as false. The code below prints out only the values which are truthy:
Converting booleans into strings
When converted to a string, booleans will return
If you want to print something other than
false, you must use conditional statements.
local enabled = false if enabled then print("Enabled") else print("Disabled") end
You can also use the following idiom to get the same results:
print(enabled and "Enabled" or "Disabled")
The not operator returns true if the argument is false or nil, otherwise it will return false.
| Value of
|| Value of |
The and operator returns the first argument if it is false or nil, otherwise it will return the second argument.
print(4 and 5) --> 5 print(nil and 13) --> nil print(false and 13) --> false print(true and true) -- true print(true and false) -- false print(false and true) -- false print(false and false) -- false
The 'or' operator operates on two values. If the first value is neither false nor nil, the 'or' operator returns the first value. If the first value is false or nil, then it will return the second value, regardless of what it is.
Choice of value
The 'or' operator can also be used to choose an default value if a value is nil or false. Here are some examples:
This printed '1' because x doesn't exist and is therefore nil. So the or operator allowed us to choose 1 over nil.
This also printed '1' because although x exists, it is false. If x had been true, then y would be true, because the 'or' operator would choose x, as it is neither false, neither nil.
A conditional expression, sometimes referred to as the ternary operator, is a substitute for a conditional statement that can be used as part of a larger expression. It allows this
local x = 100 local msg if x > 50 then msg = "is large" else msg = "is small" end msg = "your value " .. msg
To be transformed into this functionally equivalent code:
local x = 100 local msg = "your value " .. (x > 50 and "x is large" or "x is small")
It is important to note that for the general case of
cond and x or y, the code will not behave as expected if `x` is not truthy.
For more in-depth discussion of this construct, see TernaryOperator on lua-users.org.