Tables are linked together somehow

I am trying to change a the HP value inside of a table, but it somehow also changes on another table. I have no idea how to fix this however I did found out that the userid and username is not affected by this linking thing.

local coreDataTable = {
	Players = {},
}

local PlayerTemplateTable = {
	UserName = "",
	UserId = 0,
	Tempoary = {
		Tag = {},
		PlayerStatus = {
			HP = 200,
			MHP = 200,
			Stamina = 250,
			MStamina = 250,
		},
	},
}

function copyTable(tab,deep)
	local new_copy = { }

	if not deep then
		for k, v in pairs(tab) do
			new_copy[k] = v
		end
	else
		for k, v in pairs(tab) do
			new_copy[type(k) == "table" and copyTable(k) or k] = type(v) == "table" and copyTable(v) or v
		end
	end
	return new_copy
end

game:GetService("Players").PlayerAdded:Connect(function(player)
	local plrTable = copyTable(PlayerTemplateTable)
	plrTable.UserName = player.Name
	plrTable.UserId = player.UserId
	coreDataTable.Players[plrTable.UserName] = plrTable
end)
game:GetService("Players").PlayerRemoving:Connect(function(player)
	for i,v in pairs(coreDataTable.Players) do
		if v.UserId == player.UserId then
			table.remove(coreDataTable.Players,table.find(coreDataTable.Players,v))
		end
	end
end)

Code i used to test it:

local plrTable = copyTable(PlayerTemplateTable)
plrTable.UserName = "Player1"
plrTable.UserId = 1
coreDataTable.Players["Player1"] = plrTable

local plrTable2 = copyTable(PlayerTemplateTable)
plrTable2.UserName = "Player2"
plrTable2.UserId = 2
coreDataTable.Players["Player2"] = plrTable2

coreDataTable.Players["Player1"].Tempoary.PlayerStatus.HP = 10
print(coreDataTable.Players["Player2"].Tempoary.PlayerStatus.HP)
1 Like

Potentially look into using roblox’s deep copy method they gave us

local function deepCopy(original)
	local copy = {}
	for k, v in pairs(original) do
		if type(v) == "table" then
			v = deepCopy(v)
		end
		copy[k] = v
	end
	return copy
end