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.
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)
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)
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.