Lua Decision Making

Decision making in Lua is carried out via ‘if’ statements, which allow a decision to be made between two or more options.

In its most basic form, an ‘if’ statement executes a group of statements if an expression evaluates to true. Its basic syntax is as follows.

if (expression)
then
   -- Statement(s) will execute if the expression is true.
end

The following example checks whether the values of two variables are the same and displays a message in the terminal if they are.

a = 10
b = 10

if (a == b) 
then
    print("a is equal to b")
end

This can be extended to execute a statement or statements if the expression is false as follows.

if (expression)
then
   -- Statement(s) will execute if the expression is true.
else
   -- Statement(s) will execute if the expression is false.
end

This example adds an ‘else’ statement to the one above to output a message if ‘a’ and ‘b’ are not equal.

a = 10
b = 10

if (a == b) 
then
    print("a is equal to b")
else
    print("a is not equal to b")
end

The ‘if’ statement can be further extended with the use of ‘elseif’. Any number of ‘elseif’ statements can be used to extend the decision making process.

if (expression)
then
   -- Statement(s) will execute if the expression is true.
elseif (expression)
then
   --[[ Statement(s) will execute if the first expression is false
   and the second expression is true. --]]
else
   -- Statement(s) will execute if both the expressions are false.
end

Again, the above example, that compares the variables ‘a’ and ‘b’ can be extended to check if they are equal, then check if ‘a’ is greater than ‘b’ and if neither of the conditions are true, output a third message.

a = 10
b = 10

if (a == b) 
then
    print("a is equal to b")
elseif (a > b)
then
    print("a is greater than b")
else
    print("a is less than b")
end

‘if’ statements can also be nested one inside another.

if (expression)
then
   -- Statement(s) will execute if the expression is true.
   if (expression)
   then
      -- Statement(s) will execute if the expression is true.
   end
end

Below are some examples of ‘if’ statements using the logical operators discussed in the previous section on Operators.

a = true
b = true
c = false
if (a and b)
then
   -- Display a message if 'a' and 'b' are true.
   print("Condition 1 is true")
end
if (c or b)
then
   -- Display a message if 'c' or 'b' are true.
   print("Condition 2 is true")
end
if (c and b)
then
   -- Display a message if 'c' and 'b' are true.
   print("Condition 3 is true")
else
   -- Display a message if 'c' and/or 'b' are not true.
   print("Condition 3 is not true")
end
if (not(c and b))
then
   -- Display a message if 'c' and/or 'b' are not true.
   print("Condition 4 is true")
end

The results of running the above will be as follows.

Condition 1 is true
Condition 2 is true
Condition 3 is not true
Condition 4 is true