Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do you save a table to a data store?

I'm disappointed by the lack of example code ROBLOX put on the wiki for DataStores, and I need to find out how to do this properly.

2 answers

This completely depends on how you want to save it. Also, your question doesn't make it quite clear which part you do not understand! Here's some example code.

table = {"Entry1","Entry2","Entry3"} -- This is the table we will be saving.
ds = game:GetService("DataStoreService"):GetDataStore("NameOfDatastore") -- allows us to use datastore specific methods. you can add a scope if you want.

for index,value in pairs (table) do
	ds:UpdateAsync(index, function() return value end) -- index will be our 
end 

This will save it to a datastore. You can read it out by using :GetOrderedDataStore("NameOfDatastore") but that's a different question ;)

5 comments

0

This is not recursive and only works for stringy keys, does it not?

0

How else should I approach this?

0

Indeed, it is not recursive. You can also just save the whole table as a value and give it a keyname.

0

My data is currently as some instances, so would I have to save all the data under strings since you can't save instances directly?

0

Indeed, you cannot save instances. You'll have to serialize them first.

the script may contain error

local table = {a = "0",b = "0"} -- The main table
local ds = game:GetService("DataStoreService") -- datastore service
local hs = game.HttpService -- the http service
local nds = ds:GetDataStore("test")
local value = hs:JSONDecode(nds)
if value == nil then -- if it the first time you start the game then you start with the main table
	value = table
else
	value.a = value.a + 1 --we want to add 1 to a every time
	value.b = value.b + 2 --we want to add 2 to b every time
end
local encode = hs:JSONEncode(value)
hs:SetAsync("test",encode) -- may be it (encode,"test")

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