Skip to content
This repository has been archived by the owner on Sep 27, 2023. It is now read-only.

Tutorial 2.2. Loops

Adrodoc55 edited this page Oct 26, 2017 · 19 revisions

Another fundamental programming concept is the concept of loops. Up until now loops could only be created by using the command block modifier repeat. As a high level alternative MPL supports while expressions. Currently there are 3 types of while loops:

1. While loop

while: /testfor ...
repeat {
  /say I am beeing repeated
  /say me too!
}

2. Do while loop

repeat {
  /say I am beeing repeated
  /say me too!
} do while: /testfor ...

3. Infinite loop

repeat {
  /say I am beeing repeated
  /say me too!
}

Within the repeat part you can use all familiar expressions. On top of that there are the new commands break and continue, they behave just like in Java and can be conditional or inverted.

  • break will stop executing the loop and continue the program behind the loop.
  • continue will stop executing the loop, recheck the condition and then either restart the loop if the condition was successful or continue the program behind the loop if the condition failed.

You can even label loops to break or continue multiple nested loops at once. To label a loop and use the label follow this syntax:

outerLabel: while: /testfor ...
repeat {
  middleLabel: repeat {
    innerLabel: repeat {
      break outerLabel
      // continue outerLabel
    }
  } do while: /testfor ...
}

Timing

A normal loop will run once per game tick (20 times per second), but certain expressions will slow down the clock. Every expression that interrupts a normal execution flow will slow down the surrounding loop by at least one tick. If you use waitfor, intercept or call a process in a loop, the iteration frequency is undefined as it might depend on external events.

Because both break and continue can interrupt the normal execution flow, each uses up one tick even if not executed and the following loop will run once every 3 ticks:

repeat {
  // The say command is always successful
  /say hi
  invert: break
  // The next command will always fail
  /testforblock ~ ~ ~ sandstone
  conditional: continue
}

The next tutorial will cover processes, which allow you to split your code into smaller parts to better organize it: Tutorial 3. Processes.

Maybe planned

for current in @e[tag=param]
repeat (
  /execute @e[tag=current] ~ ~ ~ /say now it's my turn
  /say haha!
)