3. Booleans and Conditionals¶
Learning Objectives
- be familiar with basic boolean logic in Lua
- understand how to use conditional if-then-else statements
- be familiar with common idioms for control flow
Booleans¶
Booleans are simple: there are only two values, true
and false
. These are the building blocks for logic and flow control.
Lua provides basic comparison operators to compare values and return a boolean result:
==
(equals to)~=
(not equals to)>
(more than) and>=
(more than or equal to)<
(less than) and<=
(less than or equal to)
Lua also provides the three basic logical operators: and
, or
, and not
to allow developers to chain together conditions to form more complex conditions. These operators behave exactly the same as in other languages.
print(true and false) -- output: false
print(true or false) -- output: true
print(not true) -- output: false
if-then
statements¶
Lua if-then
statements are used to control the flow of execution based on a condition, similarly to in other programming languages.
We can also add elseif
and else
blocks for when other conditions are true or when no conditions are true respectively.
if condition1 then
-- code if condition1 is true
elseif condition2 then
-- code if condition2 is true
else
-- code if neither condition is true
end
Truthy and Falsy
false
and nil
are considered falsy values and are coerced into false when used in conditions. Likewise, true
and all other values (including 0 and "") are truthy and are coerced into true. This means that any value can be used as a condition since they all are coerced into booleans. However, incorrect usage may lead to logical errors sometimes.
One-Liner if-then
Lua lets us write one-liner if-then
statements which lets us write terser code. For instance, we might use this in a function to return early if parameters passed are incorrect.
Default values¶
Sometimes, it's useful to assign default values in case a variable is nil or doesn't meet a condition. This can be done in Lua using a common idiom:
Ternary statements¶
Ternary statements can also be written in Lua using another idiom: