Add more entries to existing tables in datastore

local userData = PlayerData:GetAsync(player.UserId)
	if not userData then
		userData = {
			characterStatistics = {
				strength = 0,
				speed = 0,
				stamina = 0,
			},
			playerStatistics = {
				ego = 0,
				xp = 0
			}
		}
		setStats(player, userData)
	else
		setStats(player, userData)
	end
	return userData

###################

	local character = player.Character 
	local save = {
		characterStatistics = {
			strength = player:GetAttribute("strength"),
			speed = player:GetAttribute("speed"),
			stamina = player:GetAttribute("stamina"),
		},
		playerStatistics = {
			ego = player:GetAttribute("ego"),
			xp = player:GetAttribute("xp")
		}
	}
	
	PlayerData:SetAsync(player.UserId, save)

I want to add lungCapacity to characterStatistics, however im not sure how I would add an entry to players with an already existing save.

2 Likes

Well what I would do is take the default data the player would get, and then add the values there, then whenever the players data loads, it takes a look at the default data, loops through all the values in the default data, and if their current data doesnt have said default data, then add it.

Sounds complicated, so heres a demonstration in code:

local defaultData = {
    Cheese = true
    Money = 5000
    Areas = {
        Area1 = true,
        Area2 = true,
        Area3 = true
    }


}

local CurrentData = { -- Example of the current data the user has
    Cheese = true
    Areas = {
        Area1 = true,
        Area2 = true,
    }
}


local function loopThroughData(data)
    for key, value in defaultData do
        if typeof(value) == 'table' then
            data[key] = loopThroughData(value)
        else
            if data[key] == nil then
                data[key] = value
            end
        end    
    end

    return data
end

CurrentData = loopThroughData(CurrentData)

what this should do is end up adding the money value, along with the Area3 value.
I spent 5 minutes on this code, as its an example, so consider creating your own version