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

Why can't I save a table with more than 1 value in my datastore?

I'm trying to save 2 values, strength and stamina. I want to save them both as a table in 1 datastore. I know this is possible, but it just isn't working. What am I doing wrong?

-- Code that gives the player their saved stats when they join
local players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

players.PlayerAdded:Connect(function(player)
	local PlayerStats = Instance.new('Folder', player)
	PlayerStats.Name = 'PlayerStats'
	local str = Instance.new('IntValue', PlayerStats)
	str.Name = 'Strength'
	local stm = Instance.new('IntValue', PlayerStats)
	stm.Name = 'Stamina'
	
	local uniquekey = "stats-"..player.userId
	local GetSaved = DSService:GetAsync(uniquekey)
	if GetSaved then
		print(GetSaved[1], GetSaved[2])
		str.Value = GetSaved[1]
		stm.Value = GetSaved[2]
	else
		DSService:SetAsync(uniquekey, {0,0})
		str.Value = 0
		stm.Value = 0
	end
end)
-- Code that saves their data when they leave
local Players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

Players.PlayerRemoving:Connect(function(player)
	local userId = "stats-"..player.userId
	local data = {player.PlayerStats.Strength.Value,player.PlayerStats.Stamina.Value}
	if data then
		local success, result = pcall(function()
			DSService:UpdateAsync(userId, data)
		end)
		if not success then
			warn(result)
		end
	end
end)

1 answer

✓ Accepted answer

#UpdateAsync()

UpdateAsync takes the 2nd parameter as a function, not a table nor value. then you'd return the new value. userId is deprecated, use UserId.

-- the other stuff

local Players = game:GetService("Players")
local DSService = game:GetService('DataStoreService'):GetDataStore('SecretTokenAboutAvatarwwww')

Players.PlayerRemoving:Connect(function(player)
    local userId = "stats-"..player.UserId
    local data = {player.PlayerStats.Strength.Value,player.PlayerStats.Stamina.Value}
	
    if data then
        local success, result = pcall(function()
   	DSService:UpdateAsync(userId, function(oldvalues)
		local newtable = data or oldvalues
		
		return newtable -- return the table
        end)

        if not success then
            warn(result)
        end
    end
end)

1 comment

0

Thanks a ton, I had no idea I had to return the value.

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