Pointers in GDScript

GDScript doesn’t have explicit pointers like Go, but we can simulate similar behavior using references to objects. Here’s an example that demonstrates the concept:

extends Node

# We'll show how references work in contrast to values with
# 2 functions: `zero_val` and `zero_ref`. `zero_val` has an
# int parameter, so arguments will be passed to it by
# value. `zero_val` will get a copy of `ival` distinct
# from the one in the calling function.
func zero_val(ival: int) -> void:
    ival = 0

# `zero_ref` in contrast has a reference to an object
# containing an integer. Changes to the object's properties
# will affect the original object.
func zero_ref(iref: Reference) -> void:
    iref.value = 0

func _ready():
    var i = 1
    print("initial:", i)
    
    zero_val(i)
    print("zero_val:", i)
    
    # Create a Reference object to hold our integer
    var ref = Reference.new()
    ref.set_meta("value", i)
    
    zero_ref(ref)
    i = ref.get_meta("value")
    print("zero_ref:", i)
    
    # In GDScript, we can't print memory addresses,
    # but we can print object IDs
    print("object id:", ref.get_instance_id())

# Create a custom Reference class to hold our integer
class IntRef:
    extends Reference
    var value: int

To run this script, save it as pointers.gd and attach it to a Node in your Godot scene. When you run the scene, you’ll see the output in the Godot output panel.

initial: 1
zero_val: 1
zero_ref: 0
object id: 1234567  # The actual number will vary

In this GDScript version:

  1. We use a Reference object to simulate a pointer. Reference is a built-in Godot class that’s passed by reference.

  2. The zero_val function works similarly to the Go version, not changing the original value.

  3. The zero_ref function changes the value in the Reference object, which is reflected in the calling function.

  4. Instead of printing memory addresses, we print the object’s instance ID, which is a unique identifier for each object in Godot.

  5. We’ve added a custom IntRef class that extends Reference to more closely mimic the behavior of the Go example. This class could be used instead of the Reference with metadata approach in the _ready function.

While GDScript doesn’t have direct pointer manipulation like Go, this example demonstrates how you can achieve similar behavior using object references.