Array unexpectedly changing itself

When an array A is inserted into an array B and one of the elements of array A is changed, the array that was inserted into array B changes to the new value of array A. Is this expected behaviour?

Code example
local varyingArray={1,2,3,4} --array that will be changed multiple times in the for loop
local arrayCollection={} --collection of arrays

for i=1, 4 do
	varyingArray[4]=i --sets the element 4 of varyingArray to i
	table.insert(arrayCollection, varyingArray) --stores varyingArray current value
end

for i, v in pairs(arrayCollection) do
	print(v) --prints each array of arrayCollection
end
Output
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 4
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 4
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 4
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 4
  }
What was supposed to be printed
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 1
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 2
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 3
  }
   ▼  {
    [1] = 1,
    [2] = 2,
    [3] = 3,
    [4] = 4
  }

I can’t post bug reports due to rank requirements, so if this isn’t expected behavior, i would be grateful if anyone did a bug report for me. If this is supposed to happen, please inform be below.

Arrays behave quite differently than other data types. When you are inserting array A into array B, you are not inserting the values of array A into array B but rather you are inserting the reference of array A into array B. It is like inserting an object into an array and changing its name. It will still be the same in each entry.

2 Likes

Tables in Lua are neither values nor variables; they are objects .

https://www.lua.org/pil/2.5.html

This is expected behavior. Tables (or variables in general) aren’t copied. @Tommybridge actually all variables behave the same. I will explain.

Think of it like a part in Workspace.

local a = part
local b = part
a.BrickColor = BrickColor.Red()
print(b.BrickColor) --> Bright red because both variables are actually the same part.

However, in most cases with variables you wouldn’t notice. Most variables can’t be changed. With the exception of tables and parts, I don’t think there’s any variable that can be changed.

local a = 5
local b = a
a = 10 -- assigning a new variable '10', not changing the existing '5'
print(b) --> 5
local a = {1, 2, 3}
local b = a
a[2] = 5
print(b[2]) --> 5 because we are changing a variable, not assigning a new one onto the other variable.
local a = {1, 2, 3}
local b = a
a = {1, 5, 3}
print(b[2]) --> 2 because we assigned a new variable, not changed an existing one.

If you need to copy a table, check this out.

2 Likes