Is there a way to know when dictionary is referencing? Like static typing, we know the type of value what the variable.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By molesallegiance

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}

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

Ertain | 2022-10-16 22:57

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.

molesallegiance | 2022-10-17 00:17

:bust_in_silhouette: Reply From: alexp

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)

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

toxicvgl | 2022-10-16 18:22

Thanks for the info…

molesallegiance | 2022-10-17 00:18

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);

molesallegiance | 2022-10-17 00:23