10. Loops

Display the same message three times. A loop repeats a block of instructions.

while unlocks after your first fully completed Script crafting job. for unlocks with Smelting research. See Equipment and research if these are still locked.

Repeat while a condition is true

ArcaneScript
public class Program : ArcaneProgram
{
    public void OnStart()
    {
        int count = 0;
        while (count < 3)
        {
            Workshop.Log.Write("Working.");
            count++;
        }
    }
}

while checks its condition, runs the block if it is true, then checks again. count++ adds 1, just like count = count + 1.

count when checkedcount < 3Action
0trueDisplay the message and set count to 1
1trueDisplay the message and set count to 2
2trueDisplay the message and set count to 3
3falseEnd the loop

Working. appears three times. Without count++, count stays at 0 and the loop cannot finish. The game stops execution when it reaches its instruction limit.

Write a counted loop with for

You can write the same loop as for (int count = 0; count < 3; count++). Put only the Write statement in the following braces.

ArcaneScript
public class Program : ArcaneProgram
{
    public void OnStart()
    {
        for (int count = 0; count < 3; count++)
        {
            Workshop.Log.Write("Working.");
        }
    }
}

Semicolons separate three parts. The first sets count to 0 once. The middle checks the condition before each iteration. The last adds 1 after each iteration.

Only the block repeats. Statements after the block run when the loop finishes.

Do not wait for mining in a loop

A loop repeats instructions immediately. Each iteration does not advance game time or complete mining. Use OnTick from the previous chapter to check mining over time.

Exercise

How would you change the while example to display Working. five times? What is count when the condition is checked for the last time?

Show example solutionHide example solution

Change count < 3 to count < 5. It displays the message at 0, 1, 2, 3 and 4. At 5, the condition is false and the loop ends.