Data is saving for two different players?

Recently, I tried to play my game with 2 players, and the result is bad. Instead of saving on one player’s datatable that is assigned with a special key, it saves on both players.

This piece of code is in a button where the player clicks on it to purchase a land.
playerdata:AddInfoToTable(player,"FarmPlots", plot.Name, "bought", true, "crop", "None")
The code above, uses the module below to create a new information in the player’s “FarmPlots” data table.

Now this is the code of the data save module

local starterdata = { FarmPlots = {nil}, AnimalPlots = {nil} }

    local sessionData = {}

    local function setupPlayerData(player)
    	local playerUserId = "Player_" .. player.UserId
    	local data
    	local success, err = pcall(function()
    	    playerData:UpdateAsync(playerUserId, function(playerData)
    		   data = playerData
            end)
        end)

    if success then
        if data then
    	-- Data exist for this player
    	sessionData[playerUserId] = data
        else
    	-- Player doesn't have existing data
    	sessionData[playerUserId] = starterdata
        end
    else
    	warn("Cannot set up data for player!")
    end
    end

    function PlayerDataManager:AddInfoToTable(player,MainTable,Table,InfoWanted1,Info1,InfoWanted2,Info2)
    local playerUserId = "Player_" .. player.UserId
    print(player) -- shows only 1 player
    sessionData[playerUserId][MainTable][Table]={[InfoWanted1]=Info1, [InfoWanted2]=Info2}
    print(HttpService:JSONEncode(sessionData)) --prints the session data's table contents
    end

when player 1 clicks on the buy button it works but it also assign the AddInfoToTable function to the other player, player 2.

This is because both players share the same table starterdata. The solution is to use a deepcopy of the table so that the player data becomes a brand new table instead of just pointing to starterdata.

Add this function to your code:

function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

And replace this line:
sessionData[playerUserId] = starterdata
With this line:
sessionData[playerUserId] = deepcopy(starterdata)

4 Likes

Thank you so much!