Skip to content

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)
local a = 2
local b = 3
print(a ~= b)    -- output: true

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.

if condition then
    -- code to execute if condition is true
end

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.

local winner = nil
...                 -- some code to find a possible winner
if winner then      -- instead of "if winner ~= nil then"
    print("Winner is" .. winner)
end
If unsure, just be explicit and write out the full condition.

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.

function divide(num, denom)
    if denom == 0 then return end

end

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:

local result = value or default
local character = player.Character or player:WaitForCharacter()

Ternary statements

Ternary statements can also be written in Lua using another idiom:

local sign = x < 0 and "negative" or "positive"