Can i prevent data loss?? using this Secure data store.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")
local tries = 2
local dataLoaded = false
local function Set(plr)
if dataLoaded then
local key = "plr-" .. plr.UserId
local count = 0
local data = {
["Coins"] = plr.leaderstats.Coins.Value,
}
local sucess, err
repeat
sucess, err = pcall(function()
myDataStore:UpdateAsync(key, function(oldValue)
local newValue = data or oldValue or 0
return newValue
end)
end)
count = count + 1
until count >= tries or sucess
if not sucess then
warn("Failed to set the value. Error code: " .. tostring(err))
return
end
else
return
end
end
local function Get(plr)
local key = "plr-" .. plr.UserId
local count = 0
local data
local sucess, err
repeat
sucess, err = pcall(function()
data = myDataStore:GetAsync(key)
end)
count = count + 1
until count >= tries or sucess
dataLoaded = true
if not sucess then
warn("Failed to read. Data. Error code: " .. tostring(err))
plr:Kick("You have been kicked your data dont loaded!")
return
end
if sucess then
if data then
return data
else
return {
["Coins"] = 0,
}
end
end
end
local function createLeaderstats(plr)
local values = Get(plr)
local leaderstats = Instance.new("Folder",plr)
leaderstats.Name = "leaderstats"
local Coins = Instance.new("IntValue", leaderstats)
Coins.Name = "Coins"
Coins.Value = 0
Coins.Value = values.Coins
end
Players.PlayerRemoving:Connect(Set)
Players.PlayerAdded:Connect(createLeaderstats)
game:BindToClose(function()
for i, v in next, game.Players:GetChildren() do
if v then
Set(v)
end
end
end)
I used :
- Update Async
- Players Kick If Loss
- Repeat Until Tries