6. Choose with conditions

Leave a different message depending on whether there are enough materials. Choosing which instructions to run based on a condition is called branching.

Write a condition

For practice, imagine four stones on a workbench and a task that needs three. These are numbers you supply yourself, not live workshop stock. The expression stones >= 3 checks whether stones is at least three.

A condition that holds gives true; one that does not gives false. The type for these two values is bool. False does not mean an error.

ComparisonMeaning
a >= bIs a at least b?
a > bIs a greater than b?
a <= bIs a at most b?
a < bIs a less than b?
a == bAre a and b equal?
a != bAre a and b different?

Distinguish assignment with = from an equality check with ==.

if and else

ArcaneScript
public class Program : ArcaneProgram
{
    public void OnStart()
    {
        int stones = 4;
        if (stones >= 3)
        {
            Workshop.Log.Write("Enough.");
        }
        else
        {
            Workshop.Log.Write("Not enough.");
        }
    }
}

If the condition in parentheses is true, the first block runs. Otherwise, the else block runs. A block is a group of instructions enclosed in braces.

Four is at least three, so this example prints Enough. The other statement does not run. Comparing the value does not change it; stones remains four.

Exercise

What message will appear if stones is two? What if it is three? Predict each result before trying it.

Show example solutionHide example solution

Two produces Not enough. Three produces Enough. The >= comparison includes the boundary value itself.

Next chapter

So far, you have supplied the numbers yourself. Next, read actual workshop stock and use the same kind of condition.