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

How Do I Make a Table Save and Load With DataStore?

Hi, I'm new to scripting and I'm trying to save a table, can someone tell me what's wrong with my script? I'm trying to save the data values in a table then have it load when you log back on, the output has no errors.

local DS = game:GetService("DataStoreService")
local playerData = DS:GetDataStore("PlayerData")

game.Players.PlayerAdded:Connect(function(player)
	local folder = Instance.new("Folder", player)
	folder.Name = "Stats"
	
	local level = Instance.new("IntValue",folder)
	level.Name = "Level"	
	
	local XP = Instance.new("IntValue",folder)
	XP.Name = "EXP"
	
	local maxXP = Instance.new("IntValue",folder)
	maxXP.Name = "MaxEXP"
	
	local stats = playerData:GetAsync(player.UserId)	
	
	if stats then
		level.Value = stats["Level"]
		XP.Value = stats["EXP"]
		maxXP.Value = stats["MaxEXP"]
	else
		level.Value = 1
		XP.Value = 0
		maxXP.Value = 100
	end
end)


game.Players.PlayerRemoving:Connect(function(player)
	local save = {}
	
	for i, v in pairs(player.Stats:GetChildren()) do
		table.insert(save, v.Value)
		print(v)
	end
	
	playerData:SetAsync(player.UserId, save)
	
end)

1 answer

✓ Accepted answer

You don't have a table structure that looks like this:

table = { "Level" = 1, etc.

but it looks like this table {1,2,1}

So either you change how the table structure works or change the script like I made for you:

Also I highly recommend using ProfileService or DataStore2 if you want to have a reliable system, because your script will cause dataloss on server errors/shutdowns

local DS = game:GetService("DataStoreService")
local playerData = DS:GetDataStore("PlayerData")

game.Players.PlayerAdded:Connect(function(player)
    local folder = Instance.new("Folder", player)
    folder.Name = "Stats"

    local level = Instance.new("IntValue",folder)
    level.Name = "Level"    

    local XP = Instance.new("IntValue",folder)
    XP.Name = "EXP"

    local maxXP = Instance.new("IntValue",folder)
    maxXP.Name = "MaxEXP"

    local stats = playerData:GetAsync(player.UserId)    

    if stats then
        level.Value = stats[1] -- first val 
        XP.Value = stats[2]
        maxXP.Value = stats[3] -- third val
    else
        level.Value = 1
        XP.Value = 0
        maxXP.Value = 100
    end
end)


game.Players.PlayerRemoving:Connect(function(player)
    local save = {}

    for i, v in pairs(player.Stats:GetChildren()) do
        table.insert(save, v.Value)
        print(v)
    end

    playerData:SetAsync(player.UserId, save)

end)

3 comments

0

Why not use JSonEncode?

0

I've never heard of that

0

DataStore2 and ProfileWrapper also don't use that

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