What I Need Help Doing
This code saves the amount of coins a player has when they leave but it doesn’t always work when a player collects a lot of coins. I was hoping someone out there knows how to improve my code so it will save the players data every time they leave.
Hey, When you use SetAsync() you should wrap it in a pcall function (protected call function). this checks for errors, and allows the rest of the code to run.
Also, when you check if the player has data, if they have data you should use UpdateAsync()
This is should also be wrapped in a pcall function. This will also probably stop the errors you were running into, as this waits for something to be returned before stopping the yield.
I hope this helped you a little, and thanks for reading, AspectType.
You’re sending too many DataStore requests. You’re not saving it when the player leaves, but rather every time they grab a coin. If you’re not familiar with DataStores, DataStore2 is a very good library to use for beginners.
How do I make an auto save 30 second loop? Sorry I’m new to scripting lua. Also, it saves when I test it on my computer but it doesnt when I play mobile.
You generally shouldn’t use autosave loops IMO. Saving the data when the player leaves or the game shuts down is enough. If you need autosave because your servers crash, do something about the crash instead.
It is not a good practice to save data only when the player joins and leave;
And it is also not necessary that the game can crash because of server.
And if you want to loop or do autosave I recommend to do it every 1 or 2 minutes because the more amount of SetAsync or UpdateAsync the more chance of script failure.
Why do all that?
Here’s an example of how I handle databases:
local temporaryData = {};
Player.PlayerAdded:Connect(function(Player)
temporaryData[Player.UserId] = {};
end);
Remote.OnServerEvent:Connect(function(Player, Info)
temporaryData[Player.UserId].Running = Info;
end);
Player.PlayerRemoving:Connect(function(Player)
local userId = Player.UserId;
wait(3); -- prevent dupe exploits that abuse the fact that updating the database yields and takes time to update
Database:UpdateAsync(userId, function(Val)
if not Val then return temporaryData; end;
for i,v in next, temporaryData do
Val[i] = v;
end;
return Val;
end);
end);
You’re better off caching the data to a temporary table, and when the player leaves you grab the information from that temporary table and update the database with the information.
Since you’re saving the data to a table and not directly to the database, there wont be any yields, queue limits, et cetera.
My data store system differs substantially from this, but that’s the basic concept.
That should fix the yield issue, the resource usage and the queue limit.
I’m unsure if this thread got an answer, but I’ll post this here anyway.