0 votes

Hi. I just stumble on new cases where I want to assign dictionary to default__dictionary. But after asking in Godot discord, some nice guy teach me that what I am doing is referencing dictionary not assign or duplicate the default_dictionary.

The question is. Is there a way to know like in c++ where "&" is using for referencing?
Below is the case that I stumble upon:

var a: int = 2;
var b: int = a;
b = 0;
print(a);
print(b);
# The output is 2 and 0

var a_dict: Dictionary = {
    "animals" : "pig"
};
var b_dict: Dictionary = a_dict;
b_dict.animals = "baboon";
b_dict = a_dict;
print(a_dict);
print(b_dict);
# The output is {animals:baboon} and {animals:baboon}
# What I want is {animals:pig} and {animals:baboon}
Godot version 3.5.1
in Engine by (61 points)

Just a suggestion: the ends of each line don't need to have a semicolon on them. Happy coding!

Yeah.. It's a habit.. Our professor make us use semicolon in every single line when we start programming, even though it's a python. I guess she want's to make our transition to other language easier.

1 Answer

+1 vote
Best answer

In GDScript, every non-primitive variable is a reference. If you want to create a new dictionary by copy, you can do:

var a_dict: Dictionary = {
    "animals" : "pig"
};
# Updated thanks to toxicvgl's comment
var b_dict := a_dict.duplicate();
#b_dict.merge(a_dict);
b_dict.animals = "baboon";
print(a_dict);
print(b_dict);

For b_dict = a_dict after assigning "baboon" in your example, if you want that to mean b_dict goes back to {animals:"pig"} you would use b_dict.merge(a_dict, overwrite=true)

by (183 points)
selected by

One can make a copy of dictionaries by Dictionary.duplicate(), too.

Thanks for the info..

Yeah.. I solve my cases with that. But I guess new way to code can't hurt you.

Let me put that again.

var a_dict: Dictionary = {
"animals" : "pig"
};
var b_dict := {};
b_dict.merge(a_dict);
#b_dict.merge(a_dict);
b_dict.animals = "baboon";
print(a_dict);
print(b_dict);
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.