Use string to access a variable

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bobokox
:warning: Old Version Published before Godot 3 was released.

Hey!

Is it possible to access a global var by defining its name with a string var?

something like this:

export var type = "coco"
#### global.+str(type) += 1

and it should do the same like this:

export var type = "coco"
if type == "coco": global.coco += 1
if type == "bana": global.bana += 1
if type == "mang": global.mang += 1
if type == "ston": global.ston += 1
if type == "wood": global.wood += 1

thank you!

:bust_in_silhouette: Reply From: YeOldeDM

Yes! You can access a member on any node by using get("coco")

export var type = "coco"
if type in global:
    global.get(type) += 1

You can also use set(var, value) the same way:

export var reset_type = "coco"
if reset_type in global:
    global.set( type, 0 )

exactly what i need!
thank you!

bobokox | 2017-04-03 23:45

Whoops. To fast!
i get an error with the first one:
Parser Error: Can’t assign to an expression

Edit:
solved it now like this:

if type in global:
			var a = global.get(type)
			a += 1
			global.set(type, a)
			print(global.get(type))

bobokox | 2017-04-03 23:51

Saved my life

Just_Ab | 2023-05-18 06:34

:bust_in_silhouette: Reply From: Omicron

If you are dealing with many vars to use… you probably want to use Dictionary type instead of doing numerous var declarations and reflexive coding…

var my_bag = {} # create an empty Dictionary
my_bag["banana"] = 0 #store initial int value
my_bag["stone"] = 0 
my_bag["gold"] = 0

then later if you have any of these items, you can update quantities with a single line of code :

var found_item = "gold" #example of any item you find

my_bag[found_item] += 1 #update stored quantities