Strange Issue with Multidimensional Array

To get straight to the point In the code I got below, when I try to add a value to a position in the “TestTable” the value either append to each inner table (using insert) or overwrite the previous value (Change value directly at index). Looking below may explain this better.

I might just be overlooking something obvious, thanks in advance.

Test System to more easily debug

function mGen.SetupWallsTest(x, y)
	local node
	
	for i = 1, y do
		local table_t = {}
		local table_v = {1}
		
		for n = 1, x do
			table.insert(table_t, table_v)
		end
		
		table.insert(TestTable, i, table_t)
	end
	
	for i = 1, y do
		for n = 1, x do
			table.insert(TestTable[i][n], 2)
		end
	end
end

image
There should only be one “2” per inner most table however, they keep on appending per loop iteration.

Actual Code

function mGen.SetupHorizontalWalls(x, y)
	local node
	
	for i = 1, y do
		local table_t = {}
		local table_v = {1}
		
		for n = 1, x do
			table.insert(table_t, table_v)
		end
		
		table.insert(HorizWalls, i, table_t)
	end
	
	for i = 1, y do
		for n = 1, x do
			if i == y and n == x then continue
			elseif i == y then continue
			elseif n == x then
				node = mGen.GenerateWallHorizontal(n,i)
				print(node)
				HorizWalls[i][n][2] = node
				--table.insert(HorizWalls[i][n], 2, node)
				continue
			else
				node = mGen.GenerateWallHorizontal(n,i)
				print(node)
				HorizWalls[i][n][2] = node
				--table.insert(HorizWalls[i][n], 2, node)
			end			
		end
	end
	print(HorizWalls)
end

Output with direct insert.
image
Values in the innermost table should be as follows
1:1 2:1 … 1:2 2:2 … etc

Separated the algorithm into two loops for the sake of testing, but just now brought them back together and it seems to have fixed itself. Still extremely strange, but for the time being I’ll just go with it. Got new issues to take care of now. :weary:

If someone can identify the actual reason for the issue above, ill change the “solution”.

Finally realized the issue to any curious people that stumble upon this.
To make things simpler when creating the main multidimensional tables, I created more or less template tables that would be nested inside, containing default values. However, as I made them into variables and tables are intrinsically passed by reference, each time I changed the value of one internal table, I changed the values within them all. Honestly not an issue I should have run into, but definitely a confusing one for people who have less experience, so hopefully this proves helpful to someone.