How to save all folders along with items that are in them into Datastore

Hello Developers,

Today, I wanted to make an folders and put in them an folders and different values, what would be the best way to save them to Data store. Since I don’t want to write bunch of mess. If you wonder why I need it, it is because I am creating an shop items, that player can purchase and so these items can save when player comes back, all of his/her items will be back. The reason I want to use folders, and values, because for me it’s easier to modify. Thanks!

So what would be best way to do so?

Convert the folders into a dictionary and save that to the DataStore.

Generally, it’s better practise to not deal with folders and leave them in tables, it’s still very easy to modify (moreso if you put it in shared)

Would able to show me an example?

shared.PlayerData = {
  ElliottLMz = { Points = 10 }
}

DataStore:SaveAsync(Player.UserId, shared.PlayerData[player.Name])
1 Like

We’re aware that you can’t save instances in datastores, which is why we perform Serialization and De-Serialization.

Serialization is where you put the data in a format that can be saved. Datastores save data by encoding the data into JSON and saving it on roblox’s servers. Strings, tables and numbers can be saved as they can be encoded into JSON, all else will have to be serialized.

Say we have two folders called Accessories and Clothing and we’d like to save them. We could make a dictionary for both, iterate over the folders and store attributes of the instances in their respective dictionaries.

local dictionary = {
    ["Accessories"]  = {} ;
    ["Clothing"]  = {};
}

for _, accessory in pairs(player.Accessories:GetChildren())  do
    table.insert(dictionary["Accessories"], v. Name) -- "Name" is one of the attributes of the accessory
end

-- Basically do the same thing for Clothing

DataStore:SetAsync(player.UserId, dictionary) 
1 Like

Any better way than repeating the code each time I add new folder? Here are my folders:

You can define a table holding the names of folders in the player to be saved and this code will iterate over them, serialize, and save the data

local needToBeSaved = {"Accessories", "Clothing"}
local dictionary = {} 

for _, folderName in pairs(needToBeSaved)  do
    dictionary[folderName]  = {}
    for _, item in pairs(player[folderName]:GetChildren()) do
        table.insert(dictionary[folderName],  item.Name) 
    end
end

DataStore:SetAsync(player.UserId, dictionary) 
2 Likes

How do you load the folders back in order?

Trying reading about the difference between pairs() and ipairs(). I’m pretty sure ipairs() loops through a table in order.