Datastore Code Review

function LoadMisc(plr)
	local key = plr.UserId
	local pets = plr:WaitForChild("Pets")

	local Data
	local succ, err = pcall(function()
		data = MiscStorage:GetAsync(key)
	end)
	
	if succ then
		for i,v in pairs(pets:GetChildren()) do
			v.Value = data[v.Name]
		end
	else
		warn(err)
	end
end

function SaveMisc(plr)
	local pets = plr:FindFirstChild("Pets")
	
	local key = plr.UserId
	
	local Data = {}
	for i,v in pairs(pets:GetChildren()) do
		Data[v.Name] = v.Value
	end
	
	local succ, err = pcall(function()
		MiscStorage:SetAsync(key, Data)
	end)
	
	if succ then
		print("succesfully saved misc items for " .. key)
	else
		warn(err)
	end
end

Players.PlayerAdded:Connect(LoadMisc)
Players.PlayerRemoving:Connect(SaveMisc)

This code works perfectly fine but I kind of want to start using UpdateAsync. How would I do so?

4 Likes

There’s an inconsistency on LoadMisc, specifically the case sensitivity of Data. I’m rather confused why this is in the scope of the function.


UpdateAsync can be found around here and how to use it.

1 Like
function SaveMisc(plr)
	local pets = plr:FindFirstChild("Pets")
	
	local key = plr.UserId
	
	local Data = {}
	for i,v in pairs(pets:GetChildren()) do
		Data[v.Name] = v.Value
	end
	
	local succ, err = pcall(function()
		if Data then
			MiscStorage:UpdateAsync(key, function(oldValue)
				local previousdata = oldValue or {DataId = 0}
					if Data.DataId == previousdata.DataId then
						Data.DataId = Data.DataId + 1
						return Data
					else
						return nil
             end
end
	
		end)
	
	if succ then
		print("succesfully saved misc items for " .. key)
	else
		warn(err)
	end
end

so something like this?

1 Like

Close enough.

The table after it should be the default data including DataId.

2 Likes

I Recommend Using a Bindable Event if a Server Unexpectedly Shutsdown or the player crashes.
Also Add local playersleft = 0
Then Add +1 to the 0 (if you have PlayerAdded Event)

game.Players.PlayerAdded:Connect(function(player)
playersleft = playersleft + 1

Heres a example of a Bindable Event.

NOTE: this will work if you have a PlayersRemoving Section.

local bindableEvent =  Instance.new('BindableEvent')
--Players Removing Section--
game:BindToClose(function()
while players left >0 do
bindableEvent.Event:Wait()
end
end)

I’m sorry, am I missing something here?

In the first function, you’ve define the local: Data however you create (not set) a new global called: data so I’m unaware of how this works?

tl;dr
(there is a variable called “Data” and when your doing the pcall your setting “data” not “Data”)

yep ive since fixed it when @Operatik mentioned it on his first reply.