Call variable with string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godot_Starter
var test = 5
var test2 = 5

func _ready():
	get("test") += test2

I want to set test to the sum of test and test2.

BUT I only have the name of the test variable as a string "test" and I cant call the test variable directly like so: test += test2. So I tried the get() function, but it seems like this is not the way to go, because I got this error

Parser Error: Can’t assign to an expression

Whats a way doing this right?

:bust_in_silhouette: Reply From: jgodfrey

You need a few more steps in there to make that work. Here’s an example:

var test = 5
var test2 = 5

func _ready():
	print(test)
	var temp = get("test")
	temp += test2
	set("test", temp)
	print(test)

That said, I’d ask why you need to access variables via their string names? As you can imagine, the above isn’t very efficient (or easy to understand). Based on what the underlying need is, there’s likely a better way to design whatever you’re doing.

My real problem was, that I had about 10 variables (lile the test var in my example) in a Script and I want to add to one of these variables the amount of another variable (like test2). To which of these 10 variables I want to add the other variable depends on what the player writes in a TextureEdit Node. This is why I want to call a variable with a string.

Your solution works great for it! Thank you!

Godot_Starter | 2020-11-20 19:04

Related, if you’re doing much of that, I’d recommend using a Dictionary where your variable names are the keys and the values are the current value of that variable.

Here’s an example:

var test = 5
var test2 = 5

func _ready():
	var vars = {} # create an empty dictionary
	vars["test"] = 5 # set the "test" item to a value of 5
	vars["some_other_var"] = 67 # add another item just because...
	vars["test"] += test2 # increment the value of the "test" item            
	print(vars["test"]) # print the new value of the test item
	print(vars) # print the entire dictionary

jgodfrey | 2020-11-20 19:41

:bust_in_silhouette: Reply From: Skyfrit

I think you should use a Dictionary, it will be much easier.

var num:Dictionary = {"test1": 2, "test2": 5}

func _ready():
	num["test1"] += num["test2"]
	print(num["test1"])

https://docs.godotengine.org/en/stable/classes/class_dictionary.html