Data-Store Problem

Pcall Betrayed Me

--[ Services ]

local Players = game:GetService("Players")
local DataStore = game:GetService("DataStoreService")

--[ Data ]

local PlayerData = DataStore:GetDataStore("PlayerData")

--[ Variables ]

local Values = {}
local Player_Manager = setmetatable({}, {__index = function() return 0 end})

--[ Load Data ]

function UserAddedToServer(Client)
	local self = Instance.new("Folder", Client)
	self.Name = "leaderstats"
	
	for _Index = 1, 2 do table.insert(Values, Instance.new("IntValue", self)) end
	if #Values > 0 then
		Values[1].Name = "Gems đź’Ž"
		Values[2].Name = "Rebirth ⛏"
	end local Data
	
	local Loaded, Errored = pcall(function()
		Data = PlayerData:GetAsync(Client.UserId)
	end) if not Loaded then return error({Client}) else 
		for _Index, V in ipairs(Values) do V.Value = Data end
	end
end

--[ Save Data ]

function UserLeftTheServer(Client) local Values = {} 
	for _Index, V in ipairs(Values) do table.insert(Client.leaderstats, V) end
	local Saved, Errored = pcall(function()
		PlayerData:SetAsync(Client.UserId, Values)	
	end) if not Saved then return {Client} end
end

--[ Call Methods ]

Players.PlayerAdded:Connect(UserAddedToServer)
Players.PlayerRemoving:Connect(UserLeftTheServer)

Could you atleast add explanation to what’s wrong with the code?

When I Loaded The Data

DataStore:GetAsync(Key)

If It were to error, It would return a table as a pcall
And I received the table whenever I run the code

Why are you using metatables? Metatables are unnecessary, and you should not have the need to insert a player’s leaderstats into an array. By doing so, your code looks confusing.

Also, you are overcomplicating pcalls with the way you are using them currently. You can simpify this section:

-- Original
	local Data
	local Loaded, Errored = pcall(function()
		Data = PlayerData:GetAsync(Client.UserId)
	end)

-- Simplified
	local success, response = pcall(PlayerData.GetAsync, PlayerData, Client.UserId)

In the simplified version, success indicates if the data was successfully fetched, and response is either the player data or the error message.

You can do the same when saving too:

-- Original
	local Saved, Errored = pcall(function()
		PlayerData:SetAsync(Client.UserId, Values)	
	end)
--Simplified
	local success, response = pcall(PlayerData.SetAsync, PlayerData, Client.UserId, Values)

Also, your code is quite confusing due to the weird formatting. Ideally, you should only have one statement per line.

Yeah sorry, I forgot to remove the metatable cause I was originally gonna use OOP.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.