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

Problem with DataStores saving data?

Can someone tell me what i am doing wrong with the datastores? (Note i did get gameservice datastore)

dpPrefix = "SaveTools"

function playerSave(player)
	if not waitForDataReady(player) then tellPlayer(player, saveErrorMessage) return end

	if (save_times[player] or 0) + 30 > tick() then tellPlayer(player, saveFastMessage) return end
	save_times[player] = tick()

	local gear = player:findFirstChild("StarterGear")
	if not gear then tellPlayer(player, saveErrorMessage) return end
	local tools = gear:GetChildren()
	local worked = false
	pcall(function ()
		local key = "user-" .. player.userId
		datastore:SetAsync(key,dpPrefix .. "Count", #tools) --Problem Area+++
		worked = true
	end)
	if not worked then tellPlayer(player, saveErrorMessage) return end
	for i, tool in pairs(tools) do
		pcall(function ()
			local key = "user-" .. player.userId
			datastore:SetAsync(key,dpPrefix .. tostring(i), tool) --Problem Area+++
		end)
	end
	tellPlayer(player, saveSuccessMessage)
end 

1 answer

✓ Accepted answer

The method SetAsync only has two parameters, the key and the data to be saved.

The setasync will set all of the data in the key so it cannot be used the way you have above in your code, we need to make a table but not a mixed table of key values and arrays. You will have to decide which is better for storing the data in for your game.

A data store cannot save objects e.g. tools, parts and models ect. You will have to convert these into a value e.g. string/int which can be saved and convert them when loading/saveing player data.

An example of how to save player data using some of the code above:-

local tmpData = {} -- a list to store our data
local key = "user-" .. player.userId -- the key the data will be saved under

 for i, tool in pairs(tools) do
	table.insert(tmpData , [some method to convert object to a value](tool)) -- inserts the value into the list
end

datastore:SetAsync(key, tmpData) -- saves the table in this example this is an array 

To load the data:-

local dS = game:GetService('DataStoreService'):GetDataStore( some name)

local plrData = dS:GetAsync('userId_' .. plr.userId) 

if plrData then
	-- player data in an array format
	for I,v in pairs(plrData) do
		print(I,v)
	end
	-- data can also be accessed as an array e.g. plrData[ index number here]
else
	-- no player data
end

Hope this helps, pls comment if you do no understand how this code works.

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