mvbg

VM_CONTEXT_PREPARE

VM_CONTEXT_PREPARE is a GBVM instruction used to assign a specific script (defined by its memory bank and address) to a designated slot, making it ready to be attached to an event or input handler.

Purpose: In Game Boy development, especially for event-driven systems, you often need to associate a piece of code with a particular trigger (e.g., a button press, an actor interaction). VM_CONTEXT_PREPARE acts as a setup step, pre-configuring a script so it can be easily activated later. This is essential for:

When VM_CONTEXT_PREPARE is called, it doesn’t execute the script immediately. Instead, it registers the script’s location (BANK and ADDR) with a SLOT in the VM’s internal context management system. This slot can then be referenced by other instructions.

Syntax:

VM_CONTEXT_PREPARE SLOT, BANK, ADDR

Usage Example: Preparing a Script for a Button Press

Imagine you want a specific script (PLAYER_ACTION_SCRIPT) to run whenever the player presses the ‘A’ button. You would first prepare this script in a slot, and then attach that slot to the ‘A’ button input using VM_INPUT_ATTACH.

; In your game initialization script:

; Define the script that will run when the A button is pressed
PLAYER_ACTION_SCRIPT:
  VM_LOAD_TEXT TEXT_A_BUTTON_PRESSED
  VM_DISPLAY_TEXT
  VM_IDLE 30 ; Display message for half a second
  VM_RET

TEXT_A_BUTTON_PRESSED:
  .TEXT "A Button Pressed!"
  .TEXT_END

; Prepare PLAYER_ACTION_SCRIPT in slot 0
VM_CONTEXT_PREPARE 0, BANK(PLAYER_ACTION_SCRIPT), PLAYER_ACTION_SCRIPT
; SLOT: 0
; BANK: The bank where PLAYER_ACTION_SCRIPT resides
; ADDR: The address of PLAYER_ACTION_SCRIPT

; Now, attach slot 0 to the A button input
; (This would typically be done in a separate VM_INPUT_ATTACH instruction)
; VM_INPUT_ATTACH .INPUT_A, 0

; ... rest of game initialization ...

In this example, VM_CONTEXT_PREPARE 0, BANK(PLAYER_ACTION_SCRIPT), PLAYER_ACTION_SCRIPT registers PLAYER_ACTION_SCRIPT with slot 0. This means that whenever slot 0 is triggered (e.g., by VM_INPUT_ATTACH), the PLAYER_ACTION_SCRIPT will be executed. This separation of preparation and attachment allows for flexible and dynamic event handling.

Analogy to other programming languages: This is analogous to creating a function pointer or a callback function and then registering it with an event listener or an input manager. For example:

It’s about setting up a callable piece of code to be invoked later in response to a specific event, without executing it immediately.