Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to save tables: Datastore?

Asked by
Code1ng 15
5 years ago
Edited 5 years ago

Okay, I understand datastore, but I heard that you needed JSON or HttpService to do this, how to use JSON?

Thanks in adnvace

1 answer

Log in to vote
0
Answered by
B_rnz 171
5 years ago

Um.. yes. I Love that spelling of yours.

Anyways... I don't know much on this, but here are the links, I can also provide an example or of something that I know.

JSON Format

JSONEncode() function transforms a Lua table into a JSON object or array and CANNOT ncode anything other than strings, numbers, tables, and booleans, anything else would error.

JSONDecode() function transforms a JSON object or array into a Lua table.

HttpService() allows HTTP requests to be sent from game servers.

Anyways, i'll show you an example I have, assuming that you already know what DatastoreService is.

We already have everything set up, and it should look something like:

01local PlayerData = {
02    Player = {Coins = 0, Level = 0, Diamonds = 0, Kills = 0};
03}
04 
05game.Players.PlayerAdded:Connect(function(plr)
06    local key = "User_"..plr.UserId
07 
08end)
09 
10game.Players.PlayerRemoving:Connect(function(plr)
11    local key = "User_".plr.UserId
12 
13end)

Okay so, what I would do is check to see if player has any existing data, if not then load the data they had previously. (checking to see if they have a prev key.)

1-- Inside of player added.
2if Datastore:GetAsync(key) ~= nil then
3    -- assign data
4else
5    -- load prev data
6end

Then you'd want to assign the table to the player:

1PlayerData[plr] = PlayerData

and load previous data which we'll be wrapping in pcall, to find any errors (I usually kick to prevent overlapping of data/loss of it, but you can return it instead..):

1local suc, msg = pcall(function()
2    wait(5)
3    PlayerData[Player] = HttpService:JSONDecode(DataStore:GetAsync(Key));
4end)
5if not suc then
6    Player:Kick(msg)
7end

Whenever the player IS leaving, you'd have something like (remember I am wrapping in pcall for any errors.):

1local success, message = pcall(function()
2    if PlayerData[Player] ~= nil then
3        DataStore:SetAsync(key, HttpService:JSONEncode(PlayerData[Player]))
4        print('Player Data set.')
5    end
6end)
7if not success then
8    print('Error: '..message)
9end

I suggest reading what I had above before even using my code, as I didnt explain the proces of it. Hoping that you'd just 'understand' what were getting here (also not going to lie, im bad at explaining things too.)

Welp, hope this helped. Have a nice day!

Ad

Answer this question