Conditions
All algorithms, and therefore code, need to take decisions based on certain conditions. In both Lua and Powerlang, we can run different code depending on different cases using the if and else directives. You've learned the basics in Directives, so if you've forgotten, be sure to re-read it. We will quickly repeat it now.
The if directive will run if a certain condition is true (or to be precise, not nil
and not false). Here's an example of an if directive that will run if everything has gone horribly wrong:
The else directive will run if the previous if directive hasn't (the condition hasn't been met). Expanding the previous example:
This will print "Yay, math is working!" as 10 plus 9 equals 19, not 21.
Various comparisons
You might've noted the use of ==
(and on previous pages, ~=
). This is called a comparison sign. A comparison sign compares two values to its left and to its right, and returns a boolean representing its result.
Therefore, 10 + 9 == 21
will actually evaluate to false
behind the scenes, and the previous example will become:
That's why it is also possible to assign the result of a comparison to a variable:
This would output "false". Now let's take a look at all available comparison signs in Powerlang.
The reason why we use ==
instead of =
for "equal to" is because =
is already reserved as a variable assigner, and it cannot serve both functions at once due to features described earlier. This is by design.
Logic gates
It is possible to combine comparison results (or booleans) using logic gates. Powerlang supports three of them: and
, or
, not
. It might be possible to guess what each one does:
It might be hard to understand like this, so here's an example of three if directives that will always run, using the logic gates:
Using logic gates makes doing multiple comparisons in one if directive very simple.
Unlike in Lua, all logic gates in an if
directive run.
For example: if 3 == 4 and 5 == 6
In Lua, only 3 == 4
would be evaluated.
In Powerlang, both 3 == 4
and 5 == 6
are evaluated.
Now that you know comparisons, let's take a look at events.
Last updated