new vairable changes the variable its a copy of

Godot Version

v4.3.stable.official [77dcf97d8]

Question

Making changes to a new dictionary (save_data) also makes changes to the original dictionary (users).
Is there a way to make changes only to the new dictionary?

I do not use any plugins on this project.
(incase someone is wondering)

Code:

func save_data():
	var save_data : Dictionary = users
	print(users)
	var keys : Array = save_data.keys()
	for a in keys.size():
		save_data[keys[a-1]]["online"] = false
	print(users)

Output:

{ "Tim": { "pass": "pepe123", "online": true}}
{ "Tim": { "pass": "pepe123", "online": false}}

Hi,

Copying a dictionary variable will indeed work like this, this is a normal behaviour.

Dictionary is a type of variable that is called “reference type”, meaning these variables work by pointing to an address in your computer. By copying a variable of a reference type, you actually copy the address, here resulting in using the same dictionary.
On the contrary, “value types” (like int or float) work with, as the name suggests, the actual value instead of a memory address.

Anyway, just wanted to let you know that your code is behaving as it should. To fix your problem, just use Dictionary.duplicate().

var save_data : Dictionary = users.duplicate()
2 Likes

Thank you for your explanation, now it makes sense.
Seems like i haven’t found out about variable types yet.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.