Datastore returning true despite there not being any data

I’m trying to achieve something that checks if a player has data or not, if they don’t it enables something. I found some solutions but the problem is a little weird, my script returns true despite there isn’t any data.

Another thing to prove that there’s no data:

Here’s the script:

local DS = game:GetService("DataStoreService")




local T = DS:GetDataStore("DidTutorial")



local data


game.Players.PlayerAdded:Connect(function(plr)
	local success, errorm = pcall(function()
		
	data = T:GetAsync(plr.UserId)
		
		
		return data 
	end)
	
	
	if success then
		
		
		
	else
		---Run the tutorial if they haven't done it before.
		plr.PlayerGui:WaitForChild("Tutorial").Frame.Visible = true
		
	end
	
end)

I assume I did something wrong with the retrieving data part, any help is appreciated.

You’re using the variable success incorrectly. The success parameter that you are referring to which is being returned by the pcall, actually indicates whether the Datastore request was successful or not, not whether the data exists or doesn’t within the Datastore.

You should be checking if the variable “data” is nil or not, and handling the tutorial accordingly i.e GetAsync will return nil for new players.

You should also verify the success variable to prevent data loss. The variable “data” can be nil in the case that the GetAsync() request failed due to external issues. You must account for this possibility in your script to avoid overwriting data.

1 Like

The data variable should be inside the PlayerAdded event/scope so its unique for each player and you must check if there’s data or no, its always returning true because you succeed to get the player’s data but you did not check if the player has data or no.

An example of how I get the player’s data:

local DataStore = DS:GetDataStore("someDataIdk")

game.Players.PlayerAdded:Connect(function(player)
    local success, data = pcall(DataStore.GetAsync, DataStore, player.UserId)

    --[[
     equivalent to:
     local success, data = pcall(function()
        return DataStore:GetAsync(userId)
     end)
    ]]

    if success then
        if data then -- player has data

        else  -- player doesn't have data, its probably his first time playing.

        end
    else
      -- retry data or tell the player that we failed to get his data.
    end

end)

Useful links:
Data Stores
Saving Player Data

2 Likes