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
IDX
: The loop counter variable. This variable’s value is decremented by 1 at the end of each iteration. The loop continues as long as this variable is not zero.LABEL
: The jump label that marks the beginning of the code block to be repeated. After each iteration, if IDX
is not zero, execution jumps back to this label.N
: The number of values to be removed from the stack upon exiting the loop. This is important for stack management, especially if the loop operates on values pushed onto the stack.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:
VAR_BLINK_COUNT
is initialized to 3
.BLINK_LOOP_START
.VM_ACTOR_EMOTE
and VM_IDLE
instructions execute.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
.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:
int blinkCount = 3; while (blinkCount > 0) { /* blink action */ blinkCount--; }
blink_count = 3; while blink_count > 0: # blink action; blink_count -= 1
It provides a structured way to repeat a block of code a predetermined number of times.