How to use DataStores with a Table

Im trying to save values inside a table using DataStores.

  local  usedID = {}
  local player_data,player_dataTable

pcall(function()
	player_data = PlayerData:GetAsync(player.UserId.."-ID")
	player_dataTable = PlayerData:GetAsync(player.UserId.."-IDTable")
end)

if player_data ~= nil then
	plrID.Value = player_data
	
else
	
end

local characters = {}


if plrID.Value == '' then

for i = 65, 90 do
characters[#characters+1] = string.char(i)
 end

for i = 0, 9 do
	characters[#characters+1] = tostring(i)
end	

local function randomString()

local result = ""

for i = 1, 10 do
	result = result..characters[math.random(#characters)]
   end

return result

  end	
plrID.Value = (randomString())
print(player.Name.."'S ID is "..plrID.Value.." . This will be useful in the Future!")
table.insert(usedID,plrID.Value)
wait(1)
for i, val in pairs(usedID)do
	print(val)
end

   elseif plrID.Value ~= nil then
    warn(player.Name.." already has a ID!")
    for i, val in pairs(usedID)do
	print(val)
   end	

end																					

     end)


      local bindableEvent = Instance.new("BindableEvent")
 game.Players.PlayerRemoving:Connect(function(player)
   pcall(function()
	PlayerData:SetAsync(player.UserId.."-ID",player.Data.ID.Value)
	PlayerData:SetAsync(player.UserId.."-IDTable",usedID)
	print("Saved Data for "..player.Name.." !")
   end)

Okay, so… what’s the issue? Is it not working? Is the data malformed? Are there any errors? You need to provide more information.

Also, I’m pretty sure you can save tables to DataStores already.

3 Likes

Im asking how to save a Table using datastores.

You can use HTTPService’s :JSONEncode() function to turn a table into a single string, and then you can shove that single string into a datastore.

To retrieve the data, use HTTPService’s :JSONDecode()

You don’t need to use JSONEncode or anything to save a table in a datastore.
Putting a table directly through SetAsync, UpdateAsync, etc works fine.

2 Likes

…have I really been putting everything into json for no reason all this time then?

uh oh😐

1 Like

Not necessarily, there is a limit to how much data can be stored and an encoded table is smaller.

Not when it comes to Roblox DataStores. Passing your table through JSONEncode inflates your byte count because DataStores already encode to a JSON(-like) format under the hood. You’re essentially double encoding in this scenario, which is unnecessary.

1 Like