Loops
When you need to do something multiple times in commands, the traditional option is to create a function and call it recursively. MCComplied offers three run-time commands that enable you to repeat code conditionally without having to touch function recursion, counters, etc.
All of these commands should be followed by either a code block or a single statement. That will be the code that runs for each iteration of the loop.
Repeating N times
To repeat code a given number of times, use the repeat
command. The repeat command takes in either an integer or another value, indicating how many times to repeat the code.
In the following example, the repeat command is used to kill 10 random cows in the world.
Repeating on a value
You can also specify an existing runtime value as the repeat
command's argument. The value will be converted to an int
if it's not already. This example is the same as above but uses the value 'prune' as the count instead.
Accessing the current iteration
Either variant of the repeat
command supports an additional argument, being the name of the value that should hold the current iteration. If one doesn't yet exist, a new global
int
value is created with the given name.
Current iteration bounds
When using the 'current iteration' value, it will begin at i - 1
where i
is the number of repetitions. It will then count down to zero (inclusive). If the current iteration is 0, you know it is the last iteration in the loop. To illustrate, this is the output of using:
Repeating while a condition is true
The while
command allows you to repeat code as long as a condition remains true. The conditions supported in the while
command are exactly the same as with regular if-statements.
The following kills random cows while there are more than 3 remaining:
Repeating over a selector
The for
command allows you to concisely iterate over every entity that matches a selector.
Offsetting position
If you wish to offset the position of the execution (similarly to using the positioned
subcommand in execute
), you can use the at
keyword after specifying the selector. This will allow you to offset the execution position.
The position is applied after being aligned to the executing entity, so facing coordinates like ^1
will be aligned properly.