Pull variable based on it's name

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

This might be a bit confusing, but I’m trying to pull a value off a variable based on it’s name. I have two variables that help with this.

weap_id (Weapon ID from 0 to 11)

weapon0
weapon1
weapon2
weapon3
Etc. (These contain the amount of ammo each weapon has)

Basically what I want the script to do is this:

if $ammo.value != weapon+weap_id:
    $ammo.value = weapon+weap_id

Attempting this give the following error, though:

Invalid get index 'weapon' (on base: 'Node (global.gd)').

Is there a way to combine these two so I can pull the value without typing each one out? I can get it to spit out the name if contained in str(). But that doesn’t help pull the data either.

:bust_in_silhouette: Reply From: Zylann

In this situation you should use an array. Arrays are lists of variables with a defined number of elements in them. Each element is associated a numeric index so you can access them using that index: GDScript basics — Godot Engine (3.1) documentation in English

So you can do something like:

var weapons = []
var weap_id = 0


func _ready():
	# Give the array a size
	_weapons.resize(11)

	# Put 100 ammo in every weapon by iterating each element
	# Note: the `len` function gives the total size of the array
	for i in len(_weapons):
		_weapons[i] = 100


func update_value():
	if $ammo.value != weapons[weap_id]:
		$ammo.value = weapons[weap_id]

However, there is also a way to specifically do what you said. IMO it’s a bad idea because it makes code harder to maintain in the long run, but you can get and set variables based on a procedural name using get and set:

 $ammo.value = get("weapons" + str(weap_id))