Lua: If and Else

Wouldn't it be useful if we could take information from io.read, and then check what the user has written, doing certain things depending on what they'd written? It sure would be swell, and we can accomplish this concept in Lua using these things called 'if' statements.

If statements consist of the keyword, if, followed by a condition (we'll figure out how to formulate these in a minute), followed by the then keyword, and then some code we want to execute if the condition is true, followed by the end keyword to tell the interpreter that we've finished the statement. So the concept looks something like this:

1
2
3
if CONDITION then
	--Code to execute if true
end

So the real gap in our knowledge here is the condition. So how do we formulate it? Well. Anything that evaluates to a true or false value can technically be a condition, and that includes boolean variables, but a typical condition consists of a value - it could be a variable, such as "number", or just a constant value, like "5" -, a conditional operator which defines a certain circumstance between two values, and then another value. There are a wide variety of conditional operators built in to Lua, but the most basic is the "is equal to" operator - indicated by two equals signs, ==. So if we wanted to check if the variable 'number' is equal to 5, we'd want to formulate a condition like this one:

1
number == 5

So now we have a condition, we can create an entire if statement! Let's do it:

1
2
3
4
5
number = 3

if number == 5 then
	--Code to execute if true
end

There are actually a whole bunch of conditional operators which specify different relationships between the two values:

  • == - Is equal to
  • ~= - Is not equal to
  • > - Is greater than
  • < - Is less than
  • >= - Is greater than or equal to
  • <= - Is less than or equal to

These are all pretty self-explanatory and are simply shoved between two values, just as we did in the example code snippet above. Try replacing the conditional operators we will use in code snippets below with some of the ones shown above, and just see what happens! You'll gain a lot of knowledge and experience from just playing around with code.

In the case of the above code snippet though, it's obviously pretty useless. We're setting a variable to a constant value and then checking if it equals another constant value. This functionality becomes much more useful, however, when we use them with varying values such as when we are handling user input.

So let's say we wanted to take the user's input, and check if they typed "Hi" to us. It's worth noting that user input is taken by io.read as a string data type, as can be tested using the type function. This means that any conditions that are comparing input received from the user, must compare it to another string. Remember that string constants are defined by double quotes, so getting the user input using io.read and checking if it's equal to "Hi" might look something like this:

1
2
3
4
5
6
io.write("Enter a message: ")
userinput = io.read()

if userinput == "Hi" then
	print("Well howdy there!")
end

On running this, you can see that everything works as expected, although it is case sensitive. But what can we do if we something else to happen if 'userinput' doesn't equal "Hi", but equals something else? Well, we could do another 'if' statement after the one above to check if the input is something else, like so:

1
2
3
4
5
6
7
8
9
io.write("Enter a message: ")
userinput = io.read()

if userinput == "Hi" then
	print("Well howdy there!")
end
if userinput == "Bye" then
	print("Goodbye!")
end

The problem with the above, however, is that it's certainly not efficient! If 'userinput' is "Hi" it is not "Bye", so our computer shouldn't have to check if it's "Bye" after determining that it's "Hi"!

The (easiest) way around this is something called elseif. It "daisy chains" on from an if statement and checks another condition if the first is not true. It is accomplished by replacing the "end" that we had previously, with "elseif", specifying a condition, using the "then" keyword, writing the code you want to execute if the "elseif" condition is true, and then writing our "end" keyword to tell it we've finished with the structure. So we could replace the inefficient code snippet shown above, with the more efficient code as follows:

1
2
3
4
5
6
7
8
io.write("Enter a message: ")
userinput = io.read()

if userinput == "Hi" then
	print("Well howdy there!")
elseif userinput == "Bye" then
	print("Goodbye!")
end

Much better! And as alluded to earlier, we can actually daisy chain these as much as we want, so we can have a (theoretically) infinite amount of elseifs! For example:

1
2
3
4
5
6
7
8
9
10
11
12
io.write("Enter a message: ")
userinput = io.read()

if userinput == "Hi" then
	print("Well howdy there!")
elseif userinput == "Bye" then
	print("Goodbye!")
elseif userinput == "Hello" then
	print("Hi!")
elseif userinput == "Hu" then
	print("Spelling error much?")
end

On running the script, you can see that it reacts differently depending on what the user inputs - it works! So we have a chain of if and else-ifs, but how do we specify what it should do if none of the conditions are met? Surely there is a way to add this functionality into our "daisy chain"...

Of course there is! It's called else. Much like elseif, we can replace end with else and then push the end to the end of our chain. Of course we don't need to specify a condition, because by definition we don't require one - this section will execute only if none of the other conditions in the chain are met. The code we want to execute in the else condition simply goes between the else and end keywords. So in the case of our very simple "AI"-type program, we might want something like the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
io.write("Enter a message: ")
userinput = io.read()

if userinput == "Hi" then
	print("Well howdy there!")
elseif userinput == "Bye" then
	print("Goodbye!")
elseif userinput == "Hello" then
	print("Hi!")
elseif userinput == "Hu" then
	print("Spelling error much?")
else
	print("I don't understand you. Sorry.")
end