Changing data in a table changes all values

  1. What do you want to achieve?
    I want to change a value in a table like this
['plr1'] = {
['Coins'] = 100
}
['plr2'] = {
['Coins'] = 0
}
['plr3'] = {
['Coins'] = 0
}
  1. What is the issue?
    It changes all the values in the table
['plr1'] = {
['Coins'] = 100
}
['plr2'] = {
['Coins'] = 100
}
['plr3'] = {
['Coins'] = 100
}
  1. What solutions have you tried so far?
    I have tried changing the value names and different combinations but I couldn’t find a solution
local ServerData = {}

local NewData = {
	['Coins'] = 0;
}

local function loadData(plr)
	local data = NewData
	ServerData[plr.Name] = data
end

local function applyData(plr)
	loadData(plr)
	if plr.Name == 'Player1' then
		ServerData[plr.Name].Coins = 100
	end
	print(plr.Name..'--'..ServerData[plr.Name].Coins)
end
game.Players.PlayerAdded:Connect(applyData)

Any help with be appreciated!

1 Like

testScript.rbxl (21.1 KB)

The issue here is because tables are reference types, so even if you set a variable to another variable which has a table value, both variables will “point” to the same object/table in memory.

Easy fix, just create a new table for each player in your loadData function directly:

local function loadData(plr)
local new = { --//Create a new table object for each player instead of pointing to an existing one
["Coins"] = 0;
}
ServerData[plr.Name] = new
end
3 Likes

Here’s a really useful function for problems like this. This is called deep copying.

local function Deepcopy(tbl)
    local ret = {}
    for k, v in pairs(tbl) do
        ret[k] = type(v) == "table" and Deepcopy(v) or v
    end
    return ret
end
4 Likes