VM_MEMSET is a GBVM instruction used to fill a block of data (variables) with a specified value within the GBVM’s memory space.
Purpose:
This instruction is the GBVM equivalent of the memset function in C/C++. It is highly useful for:
VM_MEMSET takes a starting memory address (DEST), a VALUE to fill with, and a COUNT of how many variables to fill.
Syntax:
VM_MEMSET DEST, VALUE, COUNT
DEST: The first destination variable. This is the starting point in memory where the filling operation will begin.VALUE: The value (a constant or a variable holding a value) that will be used to fill each of the COUNT variables.COUNT: The number of variables to be filled. Each variable typically occupies a fixed size (e.g., 1 byte for R_INT8, 2 bytes for R_INT16), and COUNT refers to the number of these variable units.Usage Example: Initializing an Inventory Array
Imagine you have an inventory system where VAR_INVENTORY_SLOT_0 through VAR_INVENTORY_SLOT_9 represent 10 inventory slots. When starting a new game, you want to clear all these slots by setting their values to 0 (representing empty).
; In your game initialization script:
; Inventory slot variables (must be contiguous in memory)
VAR_INVENTORY_SLOT_0:
.R_INT8 0
VAR_INVENTORY_SLOT_1:
.R_INT8 0
; ... up to VAR_INVENTORY_SLOT_9
VAR_INVENTORY_SLOT_9:
.R_INT8 0
; Variable to hold the value to fill with (e.g., 0 for empty)
VAR_EMPTY_SLOT_VALUE:
.R_INT8 0
; Clear all 10 inventory slots by setting them to 0
VM_MEMSET VAR_INVENTORY_SLOT_0, VAR_EMPTY_SLOT_VALUE, 10
; DEST: VAR_INVENTORY_SLOT_0 (start filling from here)
; VALUE: VAR_EMPTY_SLOT_VALUE (fill with the value 0)
; COUNT: 10 (fill 10 variables)
; Now all VAR_INVENTORY_SLOT_0 to VAR_INVENTORY_SLOT_9 will contain 0.
; You could also use a direct constant value if allowed by the GBVM version:
; VM_MEMSET VAR_INVENTORY_SLOT_0, 0, 10
; ... rest of game initialization ...
In this example, VM_MEMSET VAR_INVENTORY_SLOT_0, VAR_EMPTY_SLOT_VALUE, 10 efficiently sets the values of 10 contiguous inventory variables to 0. This is much more concise than setting each variable individually.
Important Note on Variable Contiguity: Similar to VM_MEMCPY, for VM_MEMSET to work correctly with COUNT > 1, the variables starting from DEST and extending for COUNT variables must be defined contiguously in your GBVM variable declaration section.
Analogy to other programming languages:
This is directly analogous to memset() in C/C++:
memset(&inventory_slot_0, 0, sizeof(uint8_t) * 10);
Or, in higher-level languages, initializing an array:
inventory_slots = [0] * 10let inventorySlots = new Array(10).fill(0);It’s about efficiently setting a block of memory to a uniform value.