Arrays affect each other in the same script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 9BitStrider

While working on the camera system for my game, I am storing values into two separate arrays:

cam_limits (The current camera limits for top, bottom, left and right)
cam_move (The final destination of the above limits when scrolling)

However, when I make a script that is SUPPOSED to trigger the scrolling, both arrays are affected.

Example:

extends Node2D

signal scrolling

#Determines player position in the game world.
var pos = Vector2()
var player_tilepos = Vector2()
var player_room = Vector2()

#Camera values
var res = Vector2()

var cam_limits = []
var cam_move = []

var cam_dir = Vector2()

var scroll = false

var scroll_spd = 4

func _ready():
	res = get_viewport_rect().size
	cam_limits = [$player/camera.limit_top, $player/camera.limit_bottom, $player/camera.limit_left, $player/camera.limit_right]
	cam_move = cam_limits
	
func _camera():
	#Calculate player position.
	pos = $player.position
	pos = Vector2(floor(pos.x), floor(pos.y))
	player_tilepos = $tiles.world_to_map(pos)
	player_room = Vector2(floor(pos.x / 256), floor(pos.y / 240))
	
	#Scroll up (Edge of screen)
	if pos.y < cam_limits[0] and !scroll:
		scroll = true
		cam_move[0] = cam_limits[0] - res.y
		cam_dir = Vector2(-1, 0)
		emit_signal("scrolling")
		
	print(cam_limits[0],cam_move[0])

func _process(delta):
	_camera()

The above code changes BOTH cam_limits[0] and cam_move[0] to -240 instead of just changing cam_move[0]. Am I doing something wrong?

:bust_in_silhouette: Reply From: kidscancode

Arrays are passed by reference. Example:

var a = [1, 2, 3]
var b = a
b[0] = 5
print(a)  # prints [5, 2, 3]

So when you do cam_move = cam_limits, you’re making cam_limits a reference to the same array as cam_move. If you want to have a second array with the same values, you can use Array.duplicate():

cam_move = cam_limits.duplicate()