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

How do I access DataStore info in the form of a dictionary?

Hello, I currently have this script in ServerScriptService

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("Wins")

game.Players.PlayerAdded:Connect(function(Player)
	local Leaderstats = Instance.new("Folder")
	Leaderstats.Name = "leaderstats"
	Leaderstats.Parent = Player
	
	local wins = Instance.new("IntValue")
	wins.Name = "Wins"
	wins.Value = DataStore:GetAsync(Player.UserId) or "0"
	wins.Parent = Leaderstats
	
	local money = Instance.new("IntValue")
	money.Name = "Money"
	money.Value = DataStore:GetAsync(Player.UserId) or "0"
	money.Parent = Player
	
	local OwnedItems = Instance.new("Folder")
	OwnedItems.Name = "OwnedItems"
	OwnedItems.Parent = Player
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local itemTable = {}
	for i, v in pairs(Player.Items:GetChildren()) do
		itemTable[v.Name] = v.Value
	end
	DataStore:SetAsync(Player.UserId,{
		["Wins"] = Player.leaderstats.Wins.Value;
		["Money"] = Player.Money.Value;
		["Items"] = itemTable;
	})
end)

How do I get the dictionary ["Items"] from the data store like I did the wins and money?

1 comment

0

Oops! Player.Items:GetChildren() in like 26 should be Player.OwnedItems:GetChildren()

1 answer

You are using GetAsync to call the dictionary on all values meaning it would error. This is the proper way to set it up:

local ds = game:GetService("DataStoreService"):GetDataStore('universekey')
local dt = {}
game.Players.PlayerAdded:Connect(function(p)
	if ds:GetAsync(p.UserId) then -- data exists?
		dt[p.Name] = ds:GetAsync(p.UserId) -- dictionary.
		-- leaderstats, example: wins.Value = dt[1]
		print('got stats')
	else
		dt[p.Name] = {["Wins"] = 0,["Money"] = 0,["Items"] = 0} -- wins money items
		print('Made new stats')
	end
end)
game.Players.PlayerRemoving:Connect(function(p)
	ds:SetAsync(p.UserId,dt[p.Name]
	dt[p.Name] = nil -- avoid memory leaks from massive table overload...
end)
game:BindToClose(function()
	for _, v in pairs(game.Players:GetChildren()) do
		ds:SetAsync(v.UserId,dt[v.Name])
	end
end)

dt would be the dictionary that handles all players and their data.

This would load a dictionary when the player is joined...

if this helped id like for it to be accepted

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