mvbg

VM_LOOP

VM_LOOP is a GBVM instruction that implements a loop construct, repeating a block of code as long as a specified counter variable is not zero.

Purpose: Loops are fundamental for repeating actions in games without writing redundant code. VM_LOOP is essential for:

The loop continues to execute the code block and then jumps back to the specified LABEL until the IDX variable becomes zero. Once IDX reaches zero, the loop terminates, and execution continues with the instruction immediately following the VM_LOOP block.

Syntax:

VM_LOOP IDX, LABEL, N

Usage Example: Repeating an Action a Specific Number of Times

Imagine you want to make a character blink 3 times. You can use VM_LOOP with a counter variable to achieve this.

; In your script:

; Variable to act as the loop counter
VAR_BLINK_COUNT:
  .R_INT8 0 ; Initialize to 0

; Set the number of blinks
VM_SET_INT8 VAR_BLINK_COUNT, 3

; Start the blink loop
BLINK_LOOP_START:
  ; Perform the blink action
  VM_ACTOR_EMOTE PLAYER_ACTOR, EMOTE_BLINK
  VM_IDLE 30 ; Wait for half a second (30 frames) for the blink animation

  ; Loop back if VAR_BLINK_COUNT is not zero
  VM_LOOP VAR_BLINK_COUNT, BLINK_LOOP_START, 0
; N is 0 as we are not removing anything from the stack in this context.

; After the loop finishes (VAR_BLINK_COUNT is 0), continue here
VM_LOAD_TEXT TEXT_BLINK_COMPLETE
VM_DISPLAY_TEXT
; ... rest of script ...

TEXT_BLINK_COMPLETE:
  .TEXT "Blinking complete!"
  .TEXT_END

In this example:

  1. VAR_BLINK_COUNT is initialized to 3.
  2. The script enters BLINK_LOOP_START.
  3. The VM_ACTOR_EMOTE and VM_IDLE instructions execute.
  4. VM_LOOP VAR_BLINK_COUNT, BLINK_LOOP_START, 0 decrements VAR_BLINK_COUNT (to 2, then 1, then 0). As long as it’s not zero, it jumps back to BLINK_LOOP_START.
  5. Once VAR_BLINK_COUNT becomes 0, the loop terminates, and execution proceeds to VM_LOAD_TEXT TEXT_BLINK_COMPLETE.

Analogy to other programming languages: VM_LOOP is analogous to a while loop or a for loop with a decrementing counter in other programming languages:

It provides a structured way to repeat a block of code a predetermined number of times.