mvbg

VM_SET_INT16

VM_SET_INT16 is a GBVM instruction used to assign a signed 16-bit integer value from a GBVM variable to a specific memory address within Work RAM (WRAM).

Purpose: WRAM is the Game Boy’s primary read/write memory, used for storing dynamic game data. VM_SET_INT16 is essential for updating 16-bit variables (which can range from -32,768 to 32,767) in WRAM with values that might have been calculated, retrieved from other sources, or modified during script execution. This is commonly used for:

Syntax:

VM_SET_INT16 ADDR, IDXA

Usage Example: Updating Player Score After Collecting Coins

Imagine your player collects coins, and each coin adds a certain value to their score. The total score is stored in WRAM_PLAYER_SCORE. You have a temporary variable VAR_COIN_VALUE that holds the value of the collected coin.

; In your script, after a coin is collected:

; Assume WRAM_PLAYER_SCORE is a label pointing to a 16-bit location in WRAM
; SECTION "WRAM Data", WRAM
; WRAM_PLAYER_SCORE:
;   .WORD 0 ; Reserve 2 bytes for a 16-bit word (initially 0)

; Assume VAR_COIN_VALUE holds the value of the collected coin (e.g., 10)
VAR_COIN_VALUE:
  .R_INT16 10

; Get current score from WRAM
VM_GET_INT16 VAR_CURRENT_SCORE, WRAM_PLAYER_SCORE

; Add coin value to current score using RPN
VM_RPN
  .R_REF_MEM .R_INT16, VAR_CURRENT_SCORE ; Push current score
  .R_REF_MEM .R_INT16, VAR_COIN_VALUE    ; Push coin value
  .R_OPERATOR +                         ; Add them
  .R_INT16                              ; Specify result as 16-bit integer
VM_STOP

; The new total score is now on top of the stack.
; Store this new total score back into WRAM_PLAYER_SCORE.
VM_SET_INT16 WRAM_PLAYER_SCORE, 0 ; The 0 is a placeholder, value taken from stack

; Now, WRAM_PLAYER_SCORE contains the updated total score.
; ... continue script ...

In this example, the current score is read, the coin value is added, and the resulting sum (which is left on the stack by the RPN block) is then written back to WRAM_PLAYER_SCORE using VM_SET_INT16. This allows for dynamic updates to game data based on in-game events.

Analogy to other programming languages: This is analogous to assigning the value of one variable to another variable in C/C++: int16_t player_score = current_score + coin_value;

Or, more specifically, writing a variable’s value to a memory address: *(int16_t*)WRAM_PLAYER_SCORE_ADDRESS = new_score_value;

It’s about taking a dynamic value from a variable and storing it into a specific 16-bit memory location.