DataStore2 saving table?

Hi,

So today i moved from DataStore to DataStore2 and since previsiously i used to save some of data using tables

I was loading table simply using GetAsync and then going through every number key and putting i as a instances:

local MyTable = {}
		
local function dataload()
	MyTable = MyDataStore:GetAsync(player.UserId)
end

	local sucess, err = pcall(dataload)

	if sucess then


    local num1 = 1
	local num2 = 2


if MyTable then
	if #MyTable >0 then
	for i = 1, #MyTable / 2 do
			 
					
					local thing = Instance.new("NumberValue")
						thing .Name = MyTable [num1]
						thing .Value = MyTable [num2]
						
	
						num1 = num1 + 2
						num2 = num1 + 1
		
		end
	end
end

How can i reach something like this in DataStore2?

also heres how i saved table:

local TableSave =  {}
    for i,v in pairs(player:WaitForChild("Folder"):GetChildren()) do
    	table.insert(TableSave, v.Name)
    	table.insert(TableSave, v.Value) -- i also put values of childrens of v but i didnt showed it here 
    end

	local function checking()
		MyDataStore:SetAsync(player.UserId, TableSave )
	end

	local sucess, err = pcall(checking)
	
	if sucess then		
	else
		print("Error while saving: "..err)
	end

How i can put everything from folder into table and then rewrite table?

Thanks for reading!

If the name in every name-value pair is unique (and it should be), you should try switching to a dictionary instead of an array. Both would take up exactly the same amount of space in terms of datastore limits as well.

So instead of:

{
    "key1", 8,
    "key2", 12
}
-- JSON = ["key1",8,"key2",12]

You can use:

{
    ["key1"] = 8,
    ["key2"] = 12
}
-- JSON = {"key1":8,"key2":12}

You can treat DataStore2 almost exactly like a normal datastore, except without a pcall.

Loading:

local DataStore2 = require(path.to.DataStore2)
local DEFAULT_TABLE = {}

-- ...later
local tableStore = DataStore2(player, "TableData")

local MyTable = tableStore:GetTable(DEFAULT_TABLE)
for key, value in pairs(MyTable) do
    local thing = Instance.new("NumberValue")
    thing.Name, thing.Value = key, value
    thing.Parent = player.Folder
end

And saving:

local tableStore = DataStore2(player, "TableData")

local TableSave = {}
for _, object in ipairs(player.Folder:GetChildren()) do
    TableSave[object.Name] = object.Value
end

tableStore:Set(TableSave)

You should definitely read the topic for DataStore2. It describes key differences from a normal datastore (gotchas) and it has documentation too.

4 Likes

Please look at already existing posts before creating a new one.

DataStore2 is literally just a regular DataStore with a more preferred method of saving.