mvbg

VM_PUSH_REFERENCE

VM_PUSH_REFERENCE is a GBVM instruction used to push the memory address (a reference) of a specified variable onto the top of the VM stack.

Purpose: While VM_PUSH_CONST pushes the value of a constant, VM_PUSH_REFERENCE pushes the location where a variable is stored. This is crucial for operations that need to directly manipulate the contents of a variable or pass a variable “by reference” to a subroutine. It is essential for:

Syntax:

VM_PUSH_REFERENCE IDX

Usage Example: Storing a Calculation Result in a Variable

This instruction is frequently used in conjunction with RPN (Reverse Polish Notation) operations to store the result of a calculation into a variable. Let’s revisit the example of adding two variables and storing the result.

; In your script:

; Variables to hold values
VAR_A:
  .R_INT16 10
VAR_B:
  .R_INT16 5
VAR_SUM:
  .R_INT16 0 ; Variable to store the sum

; Push the reference to VAR_SUM onto the stack. This tells the RPN block
; where to store its final result.
VM_PUSH_REFERENCE VAR_SUM

; Start RPN expression to calculate VAR_A + VAR_B
VM_RPN
  .R_REF_MEM .R_INT16, VAR_A ; Push value of VAR_A (10)
  .R_REF_MEM .R_INT16, VAR_B ; Push value of VAR_B (5)
  .R_OPERATOR +             ; Add them (result: 15)
  .R_INT16                  ; Specify result as 16-bit integer
  .R_REF_SET_IND            ; Store the result (15) into the reference (VAR_SUM)
VM_STOP

; Now VAR_SUM will contain 15.
; ... continue script ...

In this example:

  1. VM_PUSH_REFERENCE VAR_SUM places the memory address of VAR_SUM onto the stack. This address will be used by .R_REF_SET_IND to know where to write the final calculated value.
  2. The VM_RPN block performs the addition of VAR_A and VAR_B.
  3. .R_REF_SET_IND then takes the calculated sum (15) and the reference to VAR_SUM (which was pushed earlier) from the stack, and writes the sum into VAR_SUM’s memory location.

Analogy to other programming languages: This is analogous to passing a variable “by reference” or passing a pointer to a function in languages like C/C++:

In Python, while explicit pointers aren’t used, passing a mutable object (like a list or dictionary) to a function allows the function to modify the original object, which is conceptually similar to passing by reference. VM_PUSH_REFERENCE is about providing the means to directly affect a variable’s stored value.