Using UpdateAsync for tables

My game consists of a lot of statistics and instead of creating a datastore for each individual stat, I iterated them through a table and saved them to the datastore. The code works perfectly fine, but I’m trying to get away from using SetAsync when saving data. How would I do this with the method I’m using because every UpdateAsync tutorial I find is only setting one datastore value.

local function saveData(Player)
	
	local PlayerFolder = game.ServerStorage.Players:WaitForChild(Player.Name)
	local Stats = PlayerFolder.Stats
	
	if RunService:IsStudio()then return end
	
	local Data = {}
	
	for _,stat in pairs(Stats:GetChildren())do
		Data[stat.Name] = stat.Value
	end
	
	local success,err = pcall(function()
		DataStore:SetAsync("UserId:"..Player.UserId, Data)
	end)
	
	if success then
		print(Player.Name.."'s data has been successfully saved!")
	else
		warn("Something went wrong while saving "..Player.Name.."'s data!")
	end
end
3 Likes

It’d be pretty simple to implement.

local success, err = pcall(function())

    DataStore:UpdateAsync(userId, function(oldData) --second argument is a function with a parameter of the old value (which SetAsync can't do)

        local saveTable = oldData or {} --if old data is nil, start with a blank table
   
            for i, v in pairs(Stats:GetChildren()) do

                    saveTable[v.Name] = v.Value

            end

        return saveTable --return the data to be saved

    )

end)

Even though it’s a safer method, UpdateAsync is the much longer one. Plus, if you don’t use the previous data in some way, you really don’t need to use this function. For example, incrementing a value would be great with this as you can add a number onto the previous number. But since your post asked this, there it is.

Hope that helps!

9 Likes