Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to use pcall to prevent datastore errors?

LoadData = function(plr,Level,EXP,Coins)
	local GetData = PlayerStats:GetAsync(plr.UserId)
	if GetData then
		Level.Value = GetData[1]
		EXP.Value = GetData[2]
		Coins.Value = GetData[3]
	else
		Level.Value = 1
		EXP.Value = 0
		Coins.Value = 0
	end
end

SaveData = function(plr)
	local lstats = plr:FindFirstChild("leaderstats")
	if lstats ~= nil then
		local Level = lstats:FindFirstChild("Level")
		local EXP = plr:FindFirstChild("EXP")
		local Coins = lstats:FindFirstChild("Coins")
		if Level ~= nil and EXP ~= nil and Coins ~= nil then
			local tablestats = {
				Level.Value,
				EXP.Value,
				Coins.Value
			}
			local GetData = PlayerStats:GetAsync(plr.UserId)
			if GetData then
				PlayerStats:UpdateAsync(plr.UserId, function() return tablestats end)
			else
				PlayerStats:SetAsync(plr.UserId, tablestats)
			end
		end
	end
end

This is my current datastore script to save player data, I tried using pcall functions to prevent errors that might happen but it just broke the entire script so I removed it. How do I properly prevent errors that may occur? Is there any way to make one happen so I can see how the script handles it?

1 comment

0

local success, msg = pcall(function() end) just wrap it around the setasync/updateasync part

1 answer

Here is the code with the pcall

LoadData = function(plr,Level,EXP,Coins)
    local GetData = PlayerStats:GetAsync(plr.UserId)
    if GetData then
        Level.Value = GetData[1]
        EXP.Value = GetData[2]
        Coins.Value = GetData[3]
    else
        Level.Value = 1
        EXP.Value = 0
        Coins.Value = 0
    end
end

SaveData = function(plr)
    local lstats = plr:FindFirstChild("leaderstats")
    if lstats ~= nil then
        local Level = lstats:FindFirstChild("Level")
        local EXP = plr:FindFirstChild("EXP")
        local Coins = lstats:FindFirstChild("Coins")
        if Level ~= nil and EXP ~= nil and Coins ~= nil then
            local tablestats = {
                Level.Value,
                EXP.Value,
                Coins.Value
            }
            local GetData = PlayerStats:GetAsync(plr.UserId)
            if GetData then
                PlayerStats:UpdateAsync(plr.UserId, function() return tablestats end)
            else
                PlayerStats:SetAsync(plr.UserId, tablestats)
            end
        end
    end
end

--this is when you use it.
if pcall(LoadData) == false then
	print("An error occured when loading data")
end

if pcall(SaveData) == false then
	print("An error occured when saving data")
end

Read more https://www.lua.org/pil/8.4.html

This discussion is preserved as it was. New answers, comments, and votes are closed.