Another common feature of computer programs is making decisions. Suppose, user enters two numbers and program needs to pick largest of them. General construct "if-then-else" is given by example:
a, b = io.read('*n', '*n')
if a > b then
print(a)
else
print(b)
end
You may note it is somewhat similar to while
loop: there is a condition (a > b
in our case) - then some
code which executes if the condition is true. Just it doesn't repeat. And additionally there is different code to be
executed if condition is wrong. These parts are divided by keywords:
if {condition} then {code-for-true} else {code-for-false} end
Additionally you may have noticed we used io.read
with two arguments to read two variables in a single statement,
one after another. We'll discuss this in more details later, for now just remember this as useful trick.
For exercise, try modifying this program so that:
5.5
it prints short
6.5
it prints tall
average
Obviously this couldn't be done with single if-else
statement, so you can "nest" one conditional structure inside
any "branch" of another one:
if {something} then
if {another_check} then ...
else ... end
else ... end
Among our general problems there is similar exercise too: Minimum of Two!