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

How Can I Save Tables With DataStore2?

So, I am creating a custom admin script, and I can't figure out how to save Tables using DataStore2.

I've created a script, but it just gives me an error saying that :OnUpdate is a nil value.

ServerScript in ServerScriptService:

local DataStore2 = require(1936396537)

local bansTable = {}
local adminsTable = {}

game.Players.PlayerAdded:Connect(function(player)
	
	local admins = DataStore2("Admins",player):GetTable(adminsTable)
	local bans = DataStore2("Bans",player):GetTable(bansTable)
	
	local function updateAdminsTable(plr)
		table.insert(adminsTable,plr)
	end
	
	updateAdminsTable(player)
	
	admins:OnUpdate(updateAdminsTable)
end)

And this is the error I am getting: https://gyazo.com/a841277fc7a44676143c03d5e8483fe9

1 answer

✓ Accepted answer

DataStoreService can't save table or userdata just string. So you need to use HttpService to encode your table to a string.

Exemple script.

local PlayerService = game:GetService('Players')
local DataStoreService = game:GetService('DataStoreService')
local HttpService = game:GetService('HttpService')

local DataStore2 = DataStoreService:GetDataStore('GameData')

local SessionData = {} -- Here personally store the data of the current clients in my server.

PlayerService.PlayerAdded:Connect(function(player)
	local cid = player.UserId
	SessionData[cid] = {
		money = 0,
		items = 'default'
	}
	
	if not game:GetService('RunService'):IsStudio() then
		local get_data = DataStore2:GetAsync(cid)
		print(get_data)
		if get_data ~= nil and type(get_data) == 'string' then
			pcall(function()
				local decode = HttpService:JSONDecode(get_data)
				if type(decode) == 'table' then
					SessionData[cid] = decode
				end
			end)
		end
	end
end)

PlayerService.PlayerRemoving:Connect(function(player)
	local cid = player.UserId
	pcall(function()
		DataStore2:SetAsync(cid, HttpService:JSONEncode(SessionData[cid]))
	end)
end)

If you have any question put it below on commentaries.

2 comments

0

Thank you!

0

How do I change the values of SessionData?

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