Copyright © 2024 Sebastiaan Heins
do {
do say ("Access granted")
} when (password == "1234")
when is used to create a conditional statement.
when is followed by a boolean expression, a block of code and an optional else block.
The boolean expression is evaluated and if it is true, the block of code before is executed.
If the boolean expression is false, the else block is executed.
Example of a when statement with an else extension:
do {
do say ("Access granted")
} when (password == "1234") else {
do say ("Access denied")
}
if is also a way to do conditionals, they look and feel like the more familiar way of doing it.
do if password == "1234" then {
do say ("Access granted")
} else {
do say ("Access denied")
}
Boolean operators are used to compare values.
Boolean operators return a boolean value. (true or false)
Common boolean operators are:
==
equal to
!=
not equal to
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
&&
and
||
or
Example of a boolean expression:
do if (password == "1234" && username == "Robotnik") then {
do say ("Access granted")
}
Here password must be equal to "1234" and username must be equal to "Robotnik" for the block to be executed.
here's another example:
do if (password == "1234" || password == "4321") then {
do say ("Access granted")
}
Here password must be equal to "1234" or "4321" for the block to be executed.
here's another example:
do if (age >= 18) then {
do say ("Access granted")
}
Here age (variable) must be greater or equal to 18 for the block to be executed.
For a full list of operators, go to 2.2 Operators.
On a more advanced note, when and is is actually extension keywords.
extension keywords are functionality that can be added to a master keyword.
Info!
When vs if
When and if both act as conditionals, but when and if act very differently.
When encapsulates all code before it, so if the condition is false, ALL the code before it is not executed.
If only encapsulates the block of code after it, so if the condition is false, only the block of code after it is not executed.
Now, extensions can be put on any master keyword, not only do.
This means you can do quick conditionals with set, return, break and more.
set number = 5 when (condition)
return number when (!condition)
This is something if can't do.
We'll learn more about do extensions in a later chapter 1.6 Extensions and loops.