Can you use a variable's value in the name of another variable?

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

Sorry if the title is confusing, I don’t know how else to ask this. Basically I have five variables: p1health, p2health, p3health, p4health, and currentp (with the p standing for player). Let’s say I want to decrease the health of the current player. I want to write something like

{“p” + currentp + “health”} = {“p” + currentp + “health”} - 1

instead of

if (currentp == 1) :
p1health = p1health - 1
elif (current p == 2):
p2health = p2health -1
etc.

That way I only need one line of code instead of eight. However, I can’t figure out any syntax that will get this to work, and I don’t know how to describe my question easily enough for Google to know what I’m talking about.

Is this possible, and if so, how? Thanks in advance for any help!

To my knowledge, I don’t think that’s possible in GDScript (though it’s possible in some languages, like ActionScript 2). I think the closest thing you have for that effect is the dictionary, where you could do:

p_health["p" + currentp + "health"] -= 1    # you can use '-=' too

Although, since you can create new entries in a dictionary with that same syntax, you’ll probably want to guard against potential mistakes:

var p_name = "p" + currentp + "health"
assert( p_health.has(p_name) )  
p_health[p_name] -= 1

assert stops the game from running if the returned value is false, so if you don’t want that just replace it with an if statement.

woopdeedoo | 2018-11-03 12:25

Thank you for your response! Honestly I’ve just started this so recently that I’m not even sure what the dictionary is, so I get something new to research, yay!
Thanks again!

Solarbear | 2018-11-04 16:32

Here’s a short introduction to dictionaries in Python. GDScript dicts have different methods which you can see here.

skrx | 2018-11-04 17:37

:bust_in_silhouette: Reply From: skrx

I see three options:

  1. As mentioned in the comment, you could use a dictionary that contains the health values of all players:
    var current_player = 1
    var players = {'player1': 25, 'player2': 52}
    players['player%s' % current_player] -= 1
  1. Create separate dictionaries for each player and assign the current player’s dictionary to the current_player variable:
    var player1 = {'health': 25}  # Could also contain additional key-value pairs.
    var player2 = {'health': 52}
    var current_player = player1  # This is a reference to the player1 dictionary now.
    current_player['health'] -= 1
  1. Create nodes for your players (give them a health property) and assign the current node to the current_player variable:
    var current_player = $Player1
    current_player.health -= 1

Thanks! This is very helpful.

Solarbear | 2018-11-05 23:21