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

I dont have an idea how to wrap a script in a pcall, can anyone help me?

Hey, so I've heard from a lot of people that wrapping datastore scripts in a pcall is actually critical.

Can anyone possibly help me? I have no idea how to do it, please provide an example.

Thank you.

1 answer

Here is an example:

local currencyName = "Cash"
local dss = game:GetService("DataStoreService")
local datastore = dss:GetDataStore("CashTestStore")
game.Players.PlayerAdded:Connect(function(player)
	local folder = Instance.new("Folder",player)
	folder.Name = "leaderstats"
	local cash = Instance.new("IntValue",folder)
	cash.Name = currencyName
	local ID = currencyName.."-"..player.UserId
	local savedData = nil
	
	pcall(function() -- Code under here will be wrapped in a pcall
		savedData = datastore:GetAsync(ID)
	end)
	
	if savedData ~= nil then
		cash.Value = savedData
		print("Data loaded")
	else
		cash.Value = 100000
		print("New player to the game")
	end
end)

To wrap something in pcall, you do like in the example above, any code between the pcall(function() and the end) will be wrapped in the pcall. Edit: this doesn't include your question but I'll post it anyway. This is the script that saves when you leave the game:

game.Players.PlayerRemoving:Connect(function(player)
	local ID = currencyName.."-"..player.UserId
	datastore:SetAsync(ID,player.leaderstats[currencyName].Value)
end)

Hope you understood how it works!

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