Array variable changes its size after ready() without changing it in code

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TKT
var gridSize = Vector2( 5,5);
var gridArray = []

func  _ready( ):
    for x in range(gridSize.x):
    		for y in range(gridSize.y):
    			gridArray.append(Vector2(x,y))
	
func _physics_process(delta):
    check_food_pos2():


func check_food_pos2():
    	var emptyTiles = gridArray
    	for tail in tailNodeArray:
    		emptyTiles.erase(pix2grid(tail.position))
    	emptyTiles.erase(pix2grid(get_node("head").get_position()))
    	print(gridArray.size())
    	
    	var pos = emptyTiles[randi()%emptyTiles.size()]
    	
    	food.position = grid2pix(pos);

I am trying to understand why my array (gridArray) changes its value in print. It should be constant after its first time. However it changes its value to emptyTiles. What do you think causing this and how should i prevent it?

:bust_in_silhouette: Reply From: kidscancode

Arrays are passed by reference. So when you do var emptyTiles = gridArray both variables are pointing at the same array object.

If you want to modify emptyTiles without touching gridArray use duplicate()

var emptyTiles = gridArray.duplicate()

See Array — Godot Engine (latest) documentation in English for more information.

Thank you for the answer…It works now.

TKT | 2019-07-08 20:07