This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

So I have code that is similar to something like this:

var dict1 = {"value" : 1}
var dict2 = dict1

func _ready():
    print(dict1, dict2)
    dict2["value"] += 2
    print(dict1, dict2)

The first time, it prints the expected: {value:1}{value:1}
However, after changing dict2's value, it prints: {value:3}{value:3}

So my question is: why did dict1 also change values if I only wrote for it to happen with dict2?
And more importantly: how do I avoid this from happening?

Godot version 3.4.4
in Engine by (17 points)

1 Answer

+1 vote
Best answer

Because that's how dictionaries work - they are passed by reference. dict2 and dict1 are both references to the same dictionary object.

If you want dict2 to be a unique dictionary, you have to make a copy:

var dict1 = {"value" : 1}
var dict2 = dict1.duplicate()
by (22,191 points)
selected by

Oh, I didn't know that! Thank you

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.