Godot: For loop is making copies instead of reference

Created on 24 Mar 2018  路  4Comments  路  Source: godotengine/godot

Godot version:
3.0.2 stable

Issue description:
For loop are making copies of elements rather than a reference to the elements.
Please find an example below:

Making a for loop like this:
for i in rain:
i += Vector2(0, 50)

does not update the value of i. Any changes are lost as soon as the loop ends.
It appears to be making a copy of the elements in rain rather than a reference to them.

this however does work as it should, using references:
for i in range(rain.size()):
rain[i] += Vector2(0, 50)

archived discussion gdscript

Most helpful comment

This is expected. Vector2s are passed by value.

Compare with Arrays which are passed by reference:

var q = [[1],[2],[3],[4]]
var r = [Vector2(1,1),Vector2(2,2),Vector2(3,3),Vector2(4,4)]

func _ready():
    for i in q:
        i.pop_back()
    print(q) # prints 4 blank arrays in an array
    for i in r:
        i.x = 0
    print(r) # prints unchanged

All 4 comments

This is expected. Vector2s are passed by value.

Compare with Arrays which are passed by reference:

var q = [[1],[2],[3],[4]]
var r = [Vector2(1,1),Vector2(2,2),Vector2(3,3),Vector2(4,4)]

func _ready():
    for i in q:
        i.pop_back()
    print(q) # prints 4 blank arrays in an array
    for i in r:
        i.x = 0
    print(r) # prints unchanged

nice example @Noshyaar, helps me understand better passing by ref or value

in a for loop

  1. pass by reference: object, arrays, dictionary
  1. pass by value: int, float, vectors, string,

and this issue could be closed

Closing per @ThakeeNathees's comment. Values passed in a for loop have the same value/reference semantics as usual.

Was this page helpful?
0 / 5 - 0 ratings