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

How do i save objects with datastore?

Asked by 4 years ago

I make a armor system that stock armors in leaderstats (to simplify). Its currently a folder with a model with 2 parts and a weld inside. What i want its to save the model and it load. This is the classic data persistence script to help you :

function onPlayerEntered(player)
wait()-- Change to wait for player longer.
player:WaitForDataReady()
repeat wait() until player:FindFirstChild("leaderstats")
if player.DataReady then
if player:findFirstChild("leaderstats") then
local score = player.leaderstats:GetChildren()
for i = 1,#score do
local ScoreLoaded = player:LoadNumber(score[i].Name)
wait()
if ScoreLoaded ~= 0 then
score[i].Value = ScoreLoaded
end
end
end
end
end

function onPlayerLeaving(player)
if player:findFirstChild("leaderstats") then
local score = player.leaderstats:GetChildren()
for i = 1,#score do
player:SaveNumber(score[i].Name,score[i].Value)
end
end
end

game.Players.PlayerAdded:connect(onPlayerEntered)
game.Players.PlayerRemoving:connect(onPlayerLeaving)

0
You can't save objects in a datastore. Save the item's name(or item id if you go that route) and any relevent information about the item to the player's key in the datastore. SteelMettle1 394 — 4y

1 answer

Log in to vote
1
Answered by 4 years ago
Edited 4 years ago

well, you can make a function than takes a table or an array and turns it into a string, then make a parser that will convert the string back to it's table/object representation..

Roblox has functions that can do this, and they are defined in the HTTP service.. You can call the encoder to turn the table/object into JSON type string, and call the decoder with the string to turn it into it's lua table/object representation..

you can store the encoded string to datastore, then retrieve and use the decoder to turn it into a lua table/object..

for instance:

local http = game:GetService("HTTPService")

local data = {
    username = "scorpion",
    numbers = {10, 20, 30}
};

local json_encoded = http.JSONEncode(data)
print(json_encoded) --> "{username="scorpion", numbers = [10,20,30]}"
print(type(json_encoded) --> string

local decoded = http:JSONDecode(json_encoded)
print(type(decoded)) --> table
print(decoded.username) --> "scorpion"
print(decoded.numbers[2]) --> 20

you can learn more about the HTTP service here

0
Thx im gonna try to learn about that scorpion981 27 — 4y
0
accept answer? User#23252 26 — 4y
0
A more advanced answer than the one I gave. SteelMettle1 394 — 4y
Ad

Answer this question