If Then


Conditional statements control program flow by evaluating an expression then proceeding to one or more different "paths" depending on the result.

Lua implements conditional statements with the if-then statement, which supports several variations.

If-Then

The most simple conditional statement contains a single boolean condition that directs program flow to a branch if that condition evaluates to true.

if-then statements in Lua follow the pattern:

if [boolean expression] then
    -- execute when boolean expression is true
end

The following is a simple example of the if-then statement:

local x = 2
local y = 3

local result

if x > y then
    result = x + y
end

print(result) -- nil

It this example the values of the x and y variables are compared and, because x is not greater than y, the conditional branch is not executed, and result is not assigned a value.

If-Then-Else

In the previous example we created a block of code that is only executed if a specific condition exists. Sometimes we need a bit more control over program flow, and want program flow to take one of two paths, depending on the conditional. For this, Lua has the if-then-else statement, which follows the pattern:

if [boolean expression] then
    -- execute when boolean expression is true
else
    -- execute when boolean expression is false
end

Let's look at a simple example:

local x = 2
local y = 3

local result

if x > y then
    result = x + y
else
    result = 5
end

print(result) -- 5

If-Then-Elseif-Else

if [boolean expression #1] then
    -- execute when boolean expression #1 is true
elseif [boolean expression #2] then
    -- execute when boolean expression #2 is true
elseif [boolean expression #n] then
    -- execute when boolean expression #n is true
else -- optional
    -- execute when all boolean expressions are false
end

The expression can include any number of elseif clauses, allowing program flow to take any number of alternate paths. Note that the else clause is optional. When included this branch will execute only of all other conditionals are false.

Let's extend our example to include a second conditional statement:

local x = 2
local y = 3

local result

if x > y then
    result = x + y
elseif x < y then
    result = 10
else
    result = 5
end

print(result) -- 10

Now that we have seen how if-then statements work, the next section will take a quick look at using the and and or to perform simple conditional statements.