mvbg

VM_RESERVE

VM_RESERVE is a GBVM instruction used to explicitly manage the size of the VM stack by reserving or disposing of a specified number of values.

Purpose: The GBVM operates on a stack, where values are pushed and popped. While many instructions implicitly manage the stack (e.g., VM_PUSH_CONST adds, VM_POP removes), VM_RESERVE provides direct control over stack allocation. This is particularly useful for:

Syntax:

VM_RESERVE N

Usage Example: Managing Temporary Variables for a Complex Calculation

Imagine you have a complex calculation that requires several intermediate temporary variables. Instead of declaring global variables for these, you can reserve space on the stack, use them, and then dispose of them.

; In your script:

; Reserve 3 temporary slots on the stack
VM_RESERVE 3
; Stack: [temp_var_0, temp_var_1, temp_var_2]

; Use the reserved slots for calculations
; Example: Store 10 in temp_var_0 (top of stack)
VM_SET_INT8 0, 10 ; Assuming 0 refers to the top-most reserved slot

; Example: Store 20 in temp_var_1
VM_SET_INT8 1, 20 ; Assuming 1 refers to the next reserved slot

; Perform some calculation using these temporary variables
VM_RPN
  .R_REF_IND ; Get value from temp_var_0 (10)
  .R_REF_IND ; Get value from temp_var_1 (20)
  .R_OPERATOR + ; Add them (30)
  .R_INT8
VM_STOP

; The result (30) is now on top of the stack, above the reserved slots.
; If you want to store this result in a global variable, you would do so now.
VM_SET_INT8 VAR_GLOBAL_RESULT, 0 ; Store 30 into VAR_GLOBAL_RESULT

; Now, dispose of the 3 temporary variables and the result (4 values in total)
VM_RESERVE -4
; Stack is now back to its state before VM_RESERVE 3

; ... continue script ...

In this example, VM_RESERVE 3 creates space for three temporary variables on the stack. After using them and potentially pushing a result, VM_RESERVE -4 cleans up both the reserved slots and the result, restoring the stack to its previous state. This helps keep the stack clean and prevents unintended side effects.

Analogy to other programming languages: This is analogous to allocating and deallocating memory on the stack in C/C++ using variable declarations within a function scope, or explicitly managing a stack data structure. While high-level languages often handle this automatically, VM_RESERVE gives you direct control over the GBVM’s stack, similar to how assembly language programmers manage their stack frames.