DatastoreService: How can I add a Data Value to already existing Data?

Datastore Question:
How can I add a Data Value to already existing Data?

Okay so look, I have a datastore that has some values. I want to add a table to the already existing Data. So if a player has a value named Dollars and I want to add another value called Levels, how can I add data to a already existing Data without making a whole new Key for the player or renaming a DataStore.

2 Likes

Let’s say you have a dataStore called “MyDataStore”

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("MyDataStore")

You can use GetAsync and SetAsync in the below manner:

local function addLevelToPlayerData(playerUserId)
	local playerData = myDataStore:GetAsync(tostring(playerUserId))
	
	if playerData == nil then
		playerData = {}
	end
	
	if playerData["Levels"] == nil then
		playerData["Levels"] = 1 -- whatever value u want goes here
	end
	
	myDataStore:SetAsync(tostring(playerUserId), playerData)
end

addLevelToPlayerData(playerUserId)

Let me know if there is anything else needed!

1 Like

No, like if I was to already have values in there. How can I add more without restarting the datastore or the key? And I think I know what you mean, let’s see if it works

Once you get the loaded data you can use this function which adds values that are missing to a template table provided

local function ReconcileTable(target, template)
	for k, v in pairs(template) do
		if type(k) == "string" then
			if target[k] == nil then
				if type(v) == "table" then
					target[k] = DeepCopyTable(v)
				else
					target[k] = v
				end
			elseif type(target[k]) == "table" and type(v) == "table" then
				ReconcileTable(target[k], v)
			end
		end
	end
end

ReconcileTable(LoadedData,DataTemplate)
1 Like

It’s hard to do if

  1. You’re not using tables for data
  2. You’re not using ProfileService

If your game requires heavy data and saving i’d reccommend Profileservice, here’s an Easy Tutorial for it. Otherwise you’d have to create custom reconciling functions to fill in missing values. I’d severely reccommend using ProfileService for this as it saves data and prevents data loss etc.

1 Like

I will test it later, thanks a lot!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.