mvbg

VM_RET_FAR

VM_RET_FAR is a GBVM instruction used to return from a far call (a subroutine located in a different memory bank).

Purpose: When a VM_CALL_FAR instruction is executed, the GBVM saves the return address (including the memory bank information) on the stack and then jumps to the specified subroutine in a different bank. VM_RET_FAR is the corresponding instruction that signals the end of that subroutine’s execution. It performs the following actions:

This instruction is crucial for maintaining proper program flow when working with the Game Boy’s banked memory architecture, allowing your scripts to call and return from routines spread across different ROM banks.

Syntax:

VM_RET_FAR

VM_RET_FAR takes no arguments. It implicitly uses the return address stored on the stack by the preceding VM_CALL_FAR.

Usage Example: Returning from a Scene Initialization Routine

Let’s consider a simple scene initialization routine that sets up the background and actors for a new area. This routine might be in a separate memory bank.

; In Bank 1 (e.g., main game logic bank)

; Call the initialization routine for the Town Scene, located in Bank 2
VM_CALL_FAR BANK(TOWN_SCENE_INIT), TOWN_SCENE_INIT

; After TOWN_SCENE_INIT returns, execution continues here.
; ... rest of main game logic ...

; In Bank 2 (e.g., scene data bank)

TOWN_SCENE_INIT:
  ; Load town background
  VM_LOAD_TILESET TILESET_TOWN
  ; Place town NPCs
  VM_ACTOR_SET_POS NPC_TOWN_GUARD, 10, 5
  VM_ACTOR_SET_POS NPC_MERCHANT, 15, 8
  ; ... other town-specific setup ...

  VM_RET_FAR ; Return from the far call

In this example, VM_CALL_FAR transfers control to TOWN_SCENE_INIT in Bank 2. After TOWN_SCENE_INIT completes its setup tasks, VM_RET_FAR is executed. This causes the GBVM to pop the return address from the stack and resume execution in Bank 1 at the instruction immediately following the VM_CALL_FAR.

Important Note on Stack Cleanup: If the VM_CALL_FAR passed any arguments on the stack, you should use VM_RET_FAR_N instead of VM_RET_FAR to ensure those arguments are properly removed from the stack. VM_RET_FAR only handles the return address, not any passed arguments.

Analogy to other programming languages: This is analogous to a return statement in a function that was called from a different module or segment of a program in a system with segmented memory. It’s the counterpart to a “far call” and ensures that execution correctly resumes in the original context after the called routine has finished its work.