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.
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
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:
if
.then
to state that the action is to be performed only if the condition is true.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.
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:
if
keyword.James Bond
.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.
18.225.209.95