How do I pass variables by reference to functions?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godotuser5675
:bust_in_silhouette: Reply From: kozaluss

In gdscript you do not have control over this. All simple types go as values, all complex types go as reference.

So what should I do if I want to create a swap function.

Godotuser5675 | 2018-09-05 10:33

First You have to have two variables that will keep the reference (may be in array, in class, whatever):

var variable1
var variable2

Then Your swap function must have access to those variables (ex. array, or class) and then you can swap like this:

var tmpvar = variable1
variable1 = variable2
variable2 = tmpvar

And that should be enough to work.

kozaluss | 2018-09-05 12:13

This doesn’t not seem true, I’ve just tested in Godot 3.2

func _ready() -> void:
var derp = Vector2(0,0)
var new_derp = derping(derp)
print("derp ", derp)
print("new_derp ", new_derp)

func derping(value):
	value.x = 2
	value.y = 1
	return value

the printed values are

derp (0, 0)
new_derp (2, 1)

The original variable derp is unchanged so it seems that types like Vector2 are also passed by value… What exactly is a “simple” type?

GabrielM | 2021-01-03 02:28

do you mean built-in types?

GabrielM | 2021-01-03 02:28

Vector2 is comprised of two float components, which is a primitive type.

Everything that extends Object/Node/Reference will be passed by reference, including Array and Dictionary (container data types).

Consider supporting this Godot proposal to be able to swap any variable just like in Python: Add a method to swap two variables in GDScript · Issue #3142 · godotengine/godot-proposals · GitHub

Xrayez | 2021-12-29 13:02

Simple yet powerful answer…

thebluetropics | 2023-02-04 13:23

:bust_in_silhouette: Reply From: TyTYctA

I think you can use that for passing reference variable.

func _ready():
    	var a = 1
    	var b = 2
    	var c = {
    		'a': a,
    		'b': b,}
    	a = c['a']
    	b = c['b']
    	prints(a, b) # a = 3, b = 4
func pass_reference(i_arg:Array):
        	i_arg[0] = 3
        	i_arg[1] = 4