Making decisions

In life, we all have to make decisions. To say yes or to say no, to buy or not to buy, to shake or to stir, to... you get the point. Our apps also have to make decisions based on conditions, and Lua has provided you with a way to do so.

The if-then statement

Our first decision statement is the if-then statement. The if-then statement will perform an action based on the result of a condition. Every if-then statement follows a standard layout: test a condition, and if true, perform an action. Here's an example:

if(age < 29) then
print('You are not quite 30!'),
end

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Let's break down our if-then statement so we understand what's happening:

  1. We let our app know we are starting a decision process with the keyword if.
  2. Next, we enclose a conditional statement with a pair of parentheses. Inside the parentheses, we are comparing two values to each other using the less than operator. When comparing a text value, we need to wrap the value with quotes; otherwise, don't use any quotes.
  3. After the conditional, we use the keyword then to state that the action is to be performed only if the condition is true.
  4. Finally, we wrap up the decision process with the keyword end.

In our sample if-then statement, we are printing the string You are not quite 30! to our Corona Terminal. If our variable age was 29 or higher, nothing would be printed to the terminal.

The if-then-else statement

What should you do when you have to make more than one decision? There's a decision statement for that too—the if-then-else statement.

Every if-then-else statement has a standard layout: test a condition, and if true, perform action 1; otherwise, perform action 2. Let's take a look at an example of an if-then-else statement:

if(player == "James Bond") then
print('Drink Shaken'),
else
print('Drink Stirred'),
end

And now let's look at a breakdown of the if-then-else statement so we can understand what's happening:

  1. We start the decision process by using the if keyword.
  2. Next, we enter a conditional statement. In our sample, we are asking our app to test the variable player to the string James Bond.
  3. If the conditional statement is true, then the decision will perform the first action, which is to print Drink Shaken to our terminal. Otherwise, the decision will perform the second action (else), which says to print Drink Stirred to our terminal.

Both if-then and if-then-else statements are great for pieces of code that need to run conditionally.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.209.95