How to update a variable with a 'copy' of another variable inside a custom resource without updating the variable inside the resource

Godot Version

4.4 Beta 3

Question

First of all, sorry if the title is confusing, I don’t know how to explain my problem better.

I have a variable outside my custom resource, to which I am assigning a variable inside my custom resource

class_name CustomResource
extends Resource

@export var a : Array[Array]
class_name Player 
extends CharacterBody2D

@export var custom_resource : CustomResource
extends Node2D

var a_player_resource : Array[Array]

@onready var player : Player = $Player

func _ready() -> void:
   a_player_resource = player.custom_resource.a

But when I want to update the variable outside of my custom resource by removing a parameter inside the ‘copy’ of the variable, I end up updating both variables.

func _input(event: InputEvent) -> void:
	if event.is_action_pressed('ui_up'):
		print('In Player', player.custom_resource.a)
		print('In Node2D', a_player_resource)
		a_player_resource[0].erase(1)
        print('In Player', player.custom_resource.a)
		print('In Node2D', a_player_resource)

The output of the print ends up being:

In Player[[1, 2], [2, 1]]
In Node2D[[1, 2], [2, 1]]
In Player[[2], [2, 1]]
In Node2D[[2], [2, 1]]

This does not happen if the variable is a number and I assume also any other type of variable that is not an array or dictionary.

This also happens in 4.3.

I don’t know if this is intentional or not, if it is please let me know.

Thank you very much in advance.

Only primitives are copied when passed, all other types are passed by reference. That means that both variables store a reference to the same entry on the heap.
If you want to copy a non primitive, you can use duplicate.

See GDScript reference — Godot Engine (stable) documentation in English

1 Like

Thank you!!