Trying to use variable variables in an argument?

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

EDIT: Answered my own question.

Sorry for the poor title, but I’m not exactly sure how to word this. Essentially I’m trying to use variable variables, and I’m not sure what the syntax is in Godot (for reference, in PHP it’s PHP: Variable variables - Manual

func selectLevel(level):
   var LevelManager = get_node("/root/LevelManager")

   LevelManager.gotoScene(LevelManager.level)

I’m trying to get something to call the function selectLevel with the argument being which ever variable was selected, and have it choose the corresponding variable in LevelManager. So if the player clicks on a button that says “LevelOne”, the button sends a signal to run select_level(“LevelOne”), and then the LevelManager runs gotoScene with the argument being a different variable within LevelManager, named LevelOne.

Currently it just crashes because it’s trying to find LevelManager.level, which doesn’t exist, instead of swapping out the .level with .LevelOne.

If someone can show me what the correct method of using variable variables is in Godot, that’d be appreciated.

:bust_in_silhouette: Reply From: denxi

Apparently variable variables aren’t something that will be in GDscript at any point, but I’ve found a different way to do this. I have the initial button press pull the value of the variable I needed, then pass that value through to the function, rather than trying to have the function itself pull the value.

Button Press:

func _on_crow_pressed():
    var levelChoice = get_node("/root/LevelManager").crow
    select_level(levelChoice)

Select Level Function:

func select_level(level):
    var LevelManager = get_node("/root/LevelManager")

    LevelManager.goto_scene(level)

This works fine and is almost certainly more stable.

I think get(), set() and call() should do what you’re looking for. They don’t have the syntax of variable variables as in PHP, but they should act in a similar way.

That said, I think these should be used as a last resort, so you should probably keep your solution.

Calinou | 2019-02-05 08:47