I’m trying to create a datasave for 2 leaderstat int values using a table, I first thought that you might not be able to write intvalues into a dictionary, so I tried to indirectly get the values but it still never worked.
--Variables/Services
local Players = game:GetService("Players")
local HttpService = game:GetService("HttpService")
local DatastoreService = game:GetService("DataStoreService")
local Datastore =DatastoreService:GetDataStore("Credit_DataStore")
-- Leaderboard System
Players.PlayerAdded:Connect(function(plr)
local Leaderstats = Instance.new("Folder")
Leaderstats.Name ="leaderstats"
Leaderstats.Parent = plr
local Gems = Instance.new("IntValue")
Gems.Name ="Gems"
Gems.Parent = Leaderstats
local Level = Instance.new("IntValue")
Level.Name ="Level"
Level.Parent = Leaderstats
-- Datasaving
local Key = "Credits_"..plr.UserId
local Data
local Success,Error = pcall(function()
Data = Datastore:GetAsync(Key)
end)
if Success then
if Data ~= nil then
local UsefulData = HttpService:JSONDecode(Data)
plr.leaderstats.Gems.Value =UsefulData["Gems"]
plr.leaderstats.Level.Value =UsefulData["Level"]
print("Data got")
print(Data)
else
plr.leaderstats.Gems.Value = 0
print("Player is new")
end
else
error(plr.."'s USERDATA failed to load, ERROR: "..Error )
end
end)
Players.PlayerRemoving:connect(function(plr)
local Key = "Credits_"..plr.UserId
local Data
local TableToSave = {
}
for _,Value in ipairs(plr.leaderstats:GetChildren())do
TableToSave[Value.Name]=Value.Value
end
local UsefulData = HttpService:JSONEncode(TableToSave)
print(UsefulData)
local Success,Error = pcall(function()
Data = Datastore:SetAsync(Key,UsefulData)
end)
if Success then
print("Data Saved!")
else
error("Failed to save data.:("..Error)
end
end)
game:BindToClose(function()
local PlayersLeft = Players:GetPlayers()
for i,Player in pairs(PlayersLeft) do
local Key = "Credits_"..Player.UserId
local Data
local TableToSave = {
}
for _,Value in ipairs(Player.leaderstats:GetChildren())do
TableToSave[Value.Name]=Value.Value
end
local UsefulData = HttpService:JSONEncode(TableToSave)
print(UsefulData)
local Success,Error = pcall(function()
Data = Datastore:SetAsync(Key,UsefulData)
end)
if Success then
print("Data of "..Player.Name.." successfully saved before shutdown!")
else
error("Failed to save data. :("..Error)
end
end
end)
This is the output I keep getting, which is strange since whenever I test I test with numbers above 0 (It isn’t getting the values as it should be.) I’ve spent more than an hour trying to get it to work, if anyone has any ideas I’d appreciate their help.