10: Conditional Statements (Runtime) (If ∕ Switch) [✓] - royal-lang/rl GitHub Wiki
Royal has 2 primary conditional statements for runtime conditionals.
Those are if statements and switch statements.
If Statement
An if statement takes a boolean expression. Parentheses are optional for the expression.
An if statement must have brackets associated with it. Single-line conditionals are not allowed in Bausslang.
if BOOLEAN_EXPRESSION
{
...
}
...
if (BOOLEAN_EXPRESSION)
{
...
}
Example:
if message && message.length
{
writeln(message);
}
Switch Statement
A switch statement is different from an if statement in that its conditions are based on matching one or more values to a given value and executing a set of scopes based on those.
A case for a switch statement must either return from the function, break out of the case or goto another case.
The value to match with must be available at compile-time.
All cases must have brackets associated with them to create scopes. This is a little different from most other languages that allows them to be omitted. Royal is by design explicit about the scopes.
You can specify a default scope which will be called whenever a given value doesn't match any cases.
You can also specify a final scope which all cases will call (Except for default or cases that return)
Just like an if statement, the parentheses are optional for the value.
A value for a switch statement means either a static value or a the result of an expression.
switch (VALUE) // Or just: switch VALUE
{
case MATCHING_VALUE
{
break;
}
case MATCHING_VALUE1,MATCHING_VALUE2
{
break;
}
case MATCHING_VALUE_RANGE_1 .. MATCHING_VALUE_RANGE_2
{
goto MATCHING_VALUE_FOR_THE_CASE;
}
default
{
break;
}
final
{
break;
}
}
Example:
switch num
{
case 1
{
writeln("one");
break;
}
case 2,3
{
writeln("two or three");
break;
}
case 4 .. 10
{
writeln("four to ten");
break;
}
default
{
writefln("Some other number: %d", num);
break;
}
final
{
writefln("This number had a case: %d", num);
break;
}
}