From MZXWiki
Jump to navigation Jump to search

Loopcount is a built-in counter that keeps track of a robot's current loop iteration (invoked using the loop start command and incremented with the loop for # command). It is notable for being one of the first robot-local counters (that is, each robot maintains its own separate loopcount), and was often co-opted for this purpose outside of its normal function as a loop counter, until the port added many local counters and rendered this use redundant. Loopcount is still frequently used to fill its original role, as robotic loops are still more convenient in some situations than ad hoc loops made with labels and gotos.

Megazeux loops have some rather quirky behavior, largely derived from the fact that loop start and loop for # are autonomous commands and not markers for code blocks. For one, MZX loops cannot be nested, which should be fairly obvious since there is only one loopcount counter. Another major quirk is that loop for # is very misleading syntax compared to what the command actually does. Instead of iterating the specified number of times, the command would be better understood as "loop until loopcount >= #". Functionally, loop start sets loopcount to 0. That's all it does. loop for # searches backwards to the first loop start statement, if loopcount is less than the given value, and THEN increments it. This is backwards, and means that the value provided to the end of the loop is almost always one less than the number of iterations desired. Finally, because of the way looping is implemented with loop for # searching backwards instead of being a true branch, then if there is no loop start statement, it will search all the way back to the beginning of the program and take that as the start of the loop. However, in order to avoid resetting loopcount to 0, it immediately skips to the next command. So a loop for without a loop start will restart execution from the second line in the robot.