Is there any other way to secure this DataStore script?

I made a data store script to save multiple values I was wondering if there was any other way to further secure it.

local datastoreservice = game:GetService("DataStoreService")
local playerdata = datastoreservice:GetDataStore("Example")

local function settable(plr)
	local newplr_Stats = {}

	for _, v in pairs(game.ServerStorage:WaitForChild("ExampleDataStore"):FindFirstChild(plr.Name.."Folder")) do
		newplr_Stats[v.Name] = v.Value
	end
	return newplr_Stats
end

local function Join(plr)
	local FolderStore = Instance.new("Folder")
	FolderStore.Name = "SAVED"
	FolderStore.Parent = game.ServerStorage:WaitForChild("ExampleDataStore")

	local gems = Instance.new("IntValue")
	gems.Name = "Gems"
	gems.Value = 0
	gems.Parent = FolderStore

	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Value = 0
	cash.Parent = FolderStore
	
	-----------------------------------
	local KEY = 'Player_'..plr.UserId
	local data = playerdata:GetAsync(KEY)



	if data then
		gems.Value = data['cash']
		cash.Value = data['cash']
	else
		gems.Value = 0
		cash.Value = 0
	end
end

local function onplayerExit(plr)
	local p_stats = settable(plr)
	local s, e = pcall(function()
		local KEY = 'Player_'..plr.UserId
		playerdata:SetAsync(KEY, p_stats)
		
	end)
	if not s then
		warn("Did Not Save!"..plr.UserId)
	end
end

Use pcall in here to prevent any errors.

Again as well, but consider using UpdateAsync().

Alright thanks, are there any benefits to using updateasync rather than setasync?

I was actually wondering why people say that? I don’t see any reason to prefer UpdateAsync. UpdateAsync even is slower than SetAsync.

UpdateAsync() considers the player’s old data value before making any changes. It needs a function as the update logic, and must return either nil to cancel the update or return the new data. It’s useful to compare the data version number.

1 Like

I hope this link helps out

2 Likes