How do I keep a dictionary synced with another dictionary?

Hello! I keep user data as dictionary in my datastore. I have a Template dictionary that includes the default values that will be set when user first joins. But when I add a new value to the template table, It will not update. I want it so whenever i add any value inside the table and it does not exist in user data, it adds it to user data with its default value.

How do I do this?

1 Like

You can achieve this with a function to Reconcile the player’s data with the template.
This function is from the source code of ProfileService.

local function ReconcileTable(target, template)
	for k, v in pairs(template) do
		if type(k) == "string" then -- Only string keys will be reconciled
			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

Every time you load the player’s data you can call this function to add any missing keys.

3 Likes

It works perfectly now, Thanks!

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