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

How do I wrap this script in a pcall? Do I need to add any other things to make it work better?

--Leaderstats script for new flight simulator

local DatastoreService = game:GetService("DataStoreService"):GetDataStore("FlightwareDSS")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder",player)
	leaderstats.Name = "leaderstats"
	
	local GROUPRANK = Instance.new("StringValue",leaderstats)
	GROUPRANK.Name = "Rank"
	GROUPRANK.Value = player:GetRoleInGroup(8323568)
	
	local MINUTESFLIED = Instance.new("IntValue", leaderstats)
	MINUTESFLIED.Name = "Minutes Flown"
	MINUTESFLIED.Value = DatastoreService:GetAsync(player.UserId) or 0
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	DatastoreService:SetAsync(player.UserId, player.leaderstats["Minutes Flown"].Value)
end)

I have heard that wrapping this in a pcall is a good idea. How do I do that? Is there anything else I should consider adding? Is there a way to autosave incase the player gets kicked. I ask because apparently when the server shuts down, the PlayerRemoving function doesn't occur.

3 comments

0

I don't experience on how to do this, but I do know what pcall does. Pcall can tell you if it saved successfully or not, that way, you can try saving again if it fails, or even warn the player that data is not saving. To fix your "PlayerRemoving" issue, you use game.BindToClose as another event. When the last player leaves, it does not fire PlayerRemoving, it fires game.BindToClose

0

Ok

0

Would this work game:BindToClose(function(player) DatastoreService:SetAsync(player.UserId, player.leaderstats["Minutes Flown"].Value) end)

2 answers

✓ Accepted answer

pcall() is a function used for error catching and preventing the script from breaking if the function wrapped inside of the pcall() errors out. pcall() takes a function as its only argument and returns two values:

  • A boolean, determining if the function successfully ran. This will be false if the function errors out.
  • The error of the function, if the boolean described above is false.

The following services can be compliant with pcall() specifically because they are prone to errors:

  • DataStoreService, and all DataStores
  • MarketplaceService

When using DataStoreService:GetAsync() it is generally an excellent idea to wrap it in a function, wrapped in pcall(). This is because if the DataStore fails to give information on the key, the function will error out, and if that is not in a protected call (pcall), the script will break. The same should apply to SetAsync().

2 comments

0

It would help if you included an example, but still, much appreciated!

0

The usage of pcall() is fairly straightforward.

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