Changing a local variable inexplicably changes a global variable.

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

I have recently run into a peculiar problem. I have a global variable called board (2d array). And within a function, I have a local variable called modboard, which I set to be equal to board:
var modboard=board
Then I change something about modboard:
But for some reason, that same change is applied to board. I do not understand why that happens or how to fix that. Please help.

:bust_in_silhouette: Reply From: rustyStriker

so you see, array is usually a pointer(or a list of them), and by “copying” an array you just copy to pointer for later use, you want to actually copy the array, and its sub-arrays, to do that you need to use Array.duplicate(true) so you will have a deep copy(meaning every sub-array is also being duplicated instead of a pointer)

Thanks, that makes sense.

Mishterius | 2020-12-28 13:38