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):
func _physics_process(delta):

func check_food_pos2():
    	var emptyTiles = gridArray
    	for tail in tailNodeArray:
    	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