DRY code doesn't work like original code does.

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

In my game I have local variables stored in the MainMenu scene and global variables that are stored in an AutoLoaded GlobalScript node. What I’m trying go do: Whenever the player goes from the Level scene to the MainMenu scene I want the local variables = the global variables and for the textboxes in the main menu to contain strings of the local variables.

I’ve gotten it to work with the following code:

points = GlobalScript.PointsToWin
$Base/OptionsContainer/PointsToWin/Points.text = str(points)

I have 5 variables to update this way, so I’d prefer to turn this into a function with three arguements that I can use so I don’t repeat too much code. This is the function I came up with:

func load_value(local_var, global_var, textbox):
    local_var = global_var
    textbox.text = str(local_var)

load_value(points, GlobalScript.PointsToWin, $Base/OptionsContainer/PointsToWin/Points)

func_load() puts the correct value as a string in the textbox, but the local variable’s values are still the defaults I’ve declared earlier in the script. I verified this by making the local variables export variables and checked them in the remote tree. What do I need to do in order for func_load() to do the same thing as the original code?

:bust_in_silhouette: Reply From: Lola

Hi,
variables like floats are passed by value (copied) and not by reference so in your load_value function, local_var starts with the value you passed but is local to the scope of the function (modifying it won’t change your “true” local variable).
Notice how locally, local_var holds the right value and is put in the textbox, hence the behavior you noticed.

What you can do instead is provide the name of the variable and change it using set:

func load_value(local_var_name: String, global_var_value, textbox):
    set(local_var_name, global_var_value)
    textbox.text = str(global_var_value)