![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | Godotuser5675 |
![]() |
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
![]() |
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,}
pass_reference(c)
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
I am not normally into reviving ancient topics, but I was searching the web for “godot pass by reference” and this thread came up. (Now in 2025) this code by TyTYctA does not work because Array and Dictionary are not the same thing. So my would-be solution is:
func setifnull(a:Array, val):
if a[0]==null:
a[0]=val
print("was null, setting to: "+val)
#really should put error_log() instead of print()
func mypreinit():
var a:Array=[0]
a[0]=filename
setifnull(a,"res://levels/level1.lvl")
filename=a[0]
#set all the other defaults...
Was going to use this to load some game level defaults to prevent CTDs in case a modder breaks the game. Although in my particular case, I think I am going to do it the hard way because all the wrapping beats the purpose of my short function. Were it a longer function this might be a solution to pass by reference.