VM_MEMCPY
is a GBVM instruction used to copy a block of data (variables) from one memory location to another within the GBVM’s memory space.
Purpose: Memory copying is a fundamental operation in programming, essential for:
VM_MEMCPY
operates on GBVM variables, treating them as contiguous blocks of memory. It copies COUNT
number of variables starting from SOUR
to the location starting at DEST
.
Syntax:
VM_MEMCPY DEST, SOUR, COUNT
DEST
: The first destination variable. This is the starting point in memory where the data will be copied to.SOUR
: The first source variable. This is the starting point in memory from where the data will be copied from.COUNT
: The number of variables to be copied. 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: Saving Player Position
Imagine you have variables VAR_PLAYER_X
and VAR_PLAYER_Y
storing the player’s current coordinates. You want to implement a save point where the player’s current position is saved into VAR_SAVE_X
and VAR_SAVE_Y
.
; In your script:
; Player position variables
VAR_PLAYER_X:
.R_INT16 0
VAR_PLAYER_Y:
.R_INT16 0
; Save slot variables (must be contiguous in memory for VM_MEMCPY to work simply)
VAR_SAVE_X:
.R_INT16 0
VAR_SAVE_Y:
.R_INT16 0
; ... code that updates VAR_PLAYER_X and VAR_PLAYER_Y ...
; When player reaches a save point:
SAVE_PLAYER_POSITION:
; Copy VAR_PLAYER_X to VAR_SAVE_X, and VAR_PLAYER_Y to VAR_SAVE_Y
; Assuming VAR_PLAYER_X and VAR_PLAYER_Y are adjacent in memory,
; and VAR_SAVE_X and VAR_SAVE_Y are also adjacent.
VM_MEMCPY VAR_SAVE_X, VAR_PLAYER_X, 2
; DEST: VAR_SAVE_X
; SOUR: VAR_PLAYER_X
; COUNT: 2 (to copy VAR_PLAYER_X and VAR_PLAYER_Y)
VM_LOAD_TEXT TEXT_GAME_SAVED
VM_DISPLAY_TEXT
VM_IDLE 60
VM_RET
TEXT_GAME_SAVED:
.TEXT "Game Saved!"
.TEXT_END
In this example, VM_MEMCPY VAR_SAVE_X, VAR_PLAYER_X, 2
copies the values from VAR_PLAYER_X
and the variable immediately following it (VAR_PLAYER_Y
) to VAR_SAVE_X
and the variable immediately following it (VAR_SAVE_Y
). This effectively saves the player’s current position.
Important Note on Variable Contiguity: For VM_MEMCPY
to work as expected with COUNT > 1
, the variables involved (SOUR
and DEST
and the subsequent COUNT-1
variables) must be defined contiguously in your GBVM variable declaration section. The GBVM compiler typically lays out variables in the order they are declared.
Analogy to other programming languages:
This is directly analogous to memcpy()
in C/C++:
memcpy(&save_x, &player_x, sizeof(player_x) + sizeof(player_y));
Or, in higher-level languages, copying slices of arrays or lists:
save_position = player_position[:]
(Python slice copy)
savePosition = [...playerPosition]
(JavaScript spread operator for array copy)
It’s about block-level data transfer in memory.