Handling data reconciling

Hi everyone,
I’ve got a datastore script, works fine until I have added a new sub-table or anything new in my table, when it starts erroring - when the data is loaded, it looks for my badges yet it doesn’t find any because last time my data saved, there weren’t any.

How would I add missing keys to my data table?

Script:

local function LoadPlayerData(player)
	SetupData(player)
	wait(2)
	local tries = 0
	local success,msg,data
	
	repeat
		tries = tries + 1
		success, msg = pcall(function()
			data = playerData:GetAsync(player.UserId)
		end)
		if not success then
			wait(2)
		end
	until tries == 3 or success
	
	if success then
		if data then
			local playerLevel = data.level
			local playerXp = data.xp
			
			player.leaderstats.Level.Value = playerLevel
			
			-- create session data
			sessionData[player.UserId] = data
		else
			-- player is new
			sessionData[player.UserId] = {
				level = 0,
				xp = 0,
				badgeData = {
					JoinedFirstTime = false,
					KilledFirstPlayer = false,
					FoundWinkeyImage = false,
					ClimbedTheVent = false
				}
			}
		end
	else
		warn("Failed to load data. Error: ", msg)
	end
end

Thank you!

1 Like
local Data = {
    Money = 123,
    Candies = 10
}

local DataTemplate = {
    Money = 0,
    Candies = 0,
    Biscuits = 1
}

local function Reconcile(Data, Template)
    for key, value in pairs(Template) do
        if (not Data[key]) then 
           Data[key] = value
        end
    end
end

Reconcile(Data, DataTemplate)
print(Data) -- Would print Money - 123, Candies - 10, Biscuits - 1
1 Like

Hi,

Is there any way to make this deep reconciliation? For example, how could I reconcile this table:

local Data = {
    Currency = {
        Money = 0,
    },
    Candies = 10
}

local DataTemplate = {
    Currency = {
        Money = 0,
        Rubies = 0,
    },
    Candies = 0,
    Biscuits = 1
}