Skip to content

Loops

The same jump, only the arrow points up — and the program starts repeating a piece of itself

A loop in mlog is not a separate instruction and not a special way of writing things. It is the same jump with its arrow pointing up: at a line that has already run.

The example adds up the numbers from zero to four. Press “step” seventeen times — or “run” once, then pause.

tick 0
Set0
=
Set1
=
Operation2
=
Operation3
=
Jump -> 24
if
End5
@counter0number
countnullnull
totalnullnull

total becomes ten: 0 + 1 + 2 + 3 + 4. count stops at five — the value at which the condition stopped holding.

Part In the example What for
preparation set count 0, set total 0 clear whatever the loop will accumulate
body op add total total count the reason for all of this
step and check op add count count 1, jump move on and decide whether another iteration is needed

The check here is at the end, and that matters: the body runs at least once even if the condition was false from the start. Such a loop assembles itself, and most of the time it is the one you want.

If the body must not run at all, the check goes at the top: a jump forward, past the end of the loop, with an unconditional jump backwards at the end of the body. Two jump lines instead of one.

A program runs in an endless loop, and the second iteration does not start from a clean slate: the variables hold what was left from the first. So set count 0 is not a formality but part of the loop.

A loop with no way out is no catastrophe. A processor runs exactly as many instructions per tick as it is allowed (@ipt: two on a micro processor, eight on a logic one, twenty-five on a hyper) and gives control back to the game. It will spin for ever, and the game meanwhile goes on as usual.

Something else is bad about it: the program will never reach the other lines. Everything below the loop will never run again — the processor is busy.

Eighteen instructions on a micro processor is nine ticks, about a seventh of a second. Such a loop cannot be seen on “run”, which is why it is walked a step at a time.

The longer the loop, the less often the program returns to the top. That is not a fault but a price: logic in Mindustry has no parallelism, and the only ways to get more done are a faster processor or a shorter loop.

Unofficial fan project, not affiliated with Anuke. Mindustry sprites, fonts and translations © Anuke, used under GPL-3.0; Fira Code under OFL-1.1. Site code is GPL-3.0.