Summary

In this lesson, you learned that:

  • if condition then … end runs its block only if the condition is true. then and end decide what belongs to the block; the indentation by 4 spaces shows it to people.
  • else adds a branch for when the condition is false, and elseif (one word) adds more branches with conditions of their own. Only the first true branch runs, so the order matters. One end closes the whole statement; else if would need another one.
  • Comparison operators compare two values: ==, ~= (not !=), <, >, <= and >=. = assigns, while == compares. Texts are equal only if they match exactly. A number is never equal to a text, and comparing them with < or > is an error.
  • A variable created with local inside a block exists only until the end of the block. Create it before the if, and change it in the branches.
  • and, or and not combine conditions. Each part must be a whole comparison, and not applies only to the value right after it. Parentheses group conditions.
  • Only false and nil count as false. 0 and "" count as true. if x then asks whether x has a value (isn't nil).
  • x or default gives a default value instead of nil. condition and a or b chooses between two values, as long as a isn't false or nil.
  • An if can be nested in another if; each end closes the nearest open if.
  • A range needs two comparisons: t >= 10 and t <= 25. 10 <= t <= 25 is an error. In an elseif chain, each branch can rely on the conditions above it being false.

In the next lesson, on loops, you'll learn to make a program repeat code: for example, to go through all the days of a season.

Instructions

Practice: Hugo the trader pays 10 coins for a pumpkin lighter than 4 kg, 20 coins for one from 4 to 8 kg, and 35 coins for a heavier one. In place of the comment, write an if statement with elseif and else that sets price. With 9 kg, the program prints:

Pumpkin: 9 kg
Price: 35 coins

A pumpkin that isn't ripe is worth only half. Below your if statement, add another one that halves the price with price // 2 when the pumpkin isn't ripe (use not). Then add Hugo's bonus to the price. bonus may be nil, so use or to count a missing bonus as 0, and put that part in parentheses: (bonus or 0). The program still prints Price: 35 coins.

Try another pumpkin: change weight to 8, isRipe to false and bonus to 3. The program prints:

Pumpkin: 8 kg
Price: 13 coins

If it prints another price, check the boundaries: a pumpkin of 8 kg is still medium.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/10