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 save objects with datastore?

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)

1 comment

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.

1 answer

✓ Accepted answer

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

3 comments

0

Thx im gonna try to learn about that

0

accept answer?

0

A more advanced answer than the one I gave.

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