Is this a "good" code for datastore?

I’ve made a script based on datastore2 module for individual player storage, its writes data of player into value-objects, creating “second cache” that is easy to connect on change and also easy to change, I’m using it in every game and want to know is that right way to do it. Its seems to be quite not right, but does it actually affect anything except for little slowdown because of accessing instance values?

blankdata = {
	cash = 1000;
	lvl = 2;
        inv = {Sword = 10}--for example Sword with damage 10
}

RS = game:GetService("ReplicatedStorage")
pls = game:GetService("Players")
SS = game:GetService("ServerScriptService")
DS2 = require(SS.DataStore2)
DATA = workspace.DATA
for i,v in pairs(blankdata) do
	DS2.Combine("DATA",i)
end


pls.PlayerAdded:Connect(function(ppl)
	if DATA:FindFirstChild(ppl.UserId) then DATA[ppl.UserId]:Destroy() end
	local locdata = Instance.new("Folder")
	locdata.Name = ppl.UserId
	for i,v in pairs(blankdata) do
		if typeof(v) == "number" then
			local locstore = DS2(i,ppl)
			local val = Instance.new("NumberValue")
			val.Name = i
			val.Value = locstore:Get(v)
			val.Parent = locdata
			val.Changed:Connect(function()
				locstore:Set(val.Value)
			end)
		elseif typeof(v) == "table" then
			local locstore = DS2(i,ppl)
			local fold = Instance.new("Folder")
			local arr = locstore:Get(v)
			for i,v in pairs(arr) do
				local item = Instance.new("StringValue",fold)
				item.Name = tostring(i)
				item.Value = tostring(v)
			end
			local function getdata ()
				local res = {}
				for i,v in pairs(fold:GetChildren()) do
					res[v.Name] = v.Value
				end
				return res
			end
			fold.Name = i
			fold.Parent = locdata
			fold.ChildAdded:Connect(function()
				locstore:Set(getdata())
			end)
			fold.ChildRemoved:Connect(function()
				locstore:Set(getdata())
			end)
		elseif typeof(v) == "string" then
			local locstore = DS2(i,ppl)
			local val = Instance.new("StringValue")
			val.Name = i
			val.Value = locstore:Get(v)
			val.Parent = locdata
			val.Changed:Connect(function()
				locstore:Set(val.Value)
			end)

		end
	end
	locdata.Parent = DATA	
end)

Well, it’s something that definitely works, but you can for sure do better. A more suitable way to do this would be to use your own replication system. Check this out: ReplicaService

1 Like