Need help referencing an array in my datastore

I’ve been trying this for hours but I’m so tired and my brain is dead.

Trying to reference the data values in the script results in nil, referencing it in the module prints the proper stuff. Do I need to wait? Am I referencing it wrong? Thanks in advance.

script:

 local DataModule = require(script.Parent:WaitForChild("Data")) --modulescript w/ func
game.Players.PlayerAdded:connect(function(player)
     print(DataModule.GetData(player).Gamepasses.Character)
end)

module:

local DSS = game:GetService("DataStoreService")
local PlayerInfo = DSS:GetDataStore("PlayerInfo")

local DefaultData = {
    Money = {
		Cash = 0,
		Diamonds = 0,
	},
	
	Gamepasses = {
		Paint = false,
		Character = false,	
	},
}

local _M = {}

--Get Data
function _M.GetData(Player)
	pcall(function()
		local Key = Player.UserId
	    local Data = PlayerInfo:GetAsync(Key)
		
		if Data == nil then
	       	Data = DefaultData
		end
		--printing the variable here works fine
		return Data
	end)
end

The line “return Data” is inside the scope of the pcall, so it’s returning to that. Thus, your GetData() function doesn’t actually return anything.

Ideally, you want the pcall to only surround GetAsync and you want to use the returned values from it to determine whether or not the request was successful. Try this:

function _M.GetData(Player)
	local Data
	local Success,Error
	repeat
		Success,Error = pcall(function()
		    Data = PlayerInfo:GetAsync(Player.UserId)
		end)
		if not Success then
			print("There was an issue loading "..Player.Name.."'s data: "..Error)
			wait(7)
		end
	until Success or not Player or not Player.Parent
	
	if Player and Player.Parent then
		if Data == nil then
	       	Data = {
			    Money = {
					Cash = 0,
					Diamonds = 0,
				},
				Gamepasses = {
					Paint = false,
					Character = false,	
				}
			}
		end
		
		return Data
	end
end
3 Likes

Well that explains why everything I tried was like running into a brick wall.

Thanks a lot man, I really appreciate the explanation and the proper way to deal with any errors.

2 Likes

By the way you do not need to do this:

Success,Error = pcall(function()
    Data = PlayerInfo:GetAsync(Player.UserId)
end)

you can just use

Success,Error = pcall(PlayerInfo.GetAsync,PlayerInfo,Player.UserId)
--example case
if Success then
local Data = Error
end

avoids the unnecessary function and assignment

1 Like