The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes
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?

in Engine by (378 points)

2 Answers

+1 vote
Best answer

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

var test = 5
var test2 = 5

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

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.

by (22,674 points)
selected by

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!

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
0 votes

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"]

by (618 points)
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.