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

Getting a nil value from a datastore?

local DataStoreService = game:GetService("DataStoreService")
local MainDataStore = DataStoreService:GetDataStore("MainDataStore")

local playerUserId = "Player_"..player.UserId
	
	local MainData
	local success, errormessage = pcall(function()
		MainData = MainDataStore:GetAsync(playerUserId)
	end)
		
	if success then
		print("Loaded in successfully")
		print(MainData)
		totalPeopleInfected.Value = MainData["TotalInfected"]
		peopleInfected.Value = MainData["Infected"]
		money.Value = MainData["Money"]
		survivors.Value = MainData["Survivors"]
		totalSurvivors.Value = MainData["TotalSurvivors"]
	else
		print("There was an error retrieving data")
		warn(errormessage)
	end

It does the success part of the if statement but then I get this error

  09:27:11.667 - ServerScriptService.Leaderstats:91: attempt to index nil with 'TotalInfected'

Any ideas? (This is in a player added function, I only copied the neccessey parts)

4 comments

0

On your line "print(MainData)" does it print "nil"?

0

yes

0

i would assume that it didn't save correctly, because it looks like the loading works fine

0

Yeah maybe the table is not saved as the way it get received.

2 answers

local DataStoreService = game:GetService("DataStoreService")
local MainDataStore = DataStoreService:GetDataStore("MainDataStore")

local playerUserId = "Player_"..player.UserId

    local success, mainData = pcall(function()--The second argument will be what is returned from the function
        return MainDataStore:GetAsync(playerUserId)
    end)

    if success and mainData then
        print("Loaded in successfully")
        print(MainData)
        totalPeopleInfected.Value = MainData["TotalInfected"]
        peopleInfected.Value = MainData["Infected"]
        money.Value = MainData["Money"]
        survivors.Value = MainData["Survivors"]
        totalSurvivors.Value = MainData["TotalSurvivors"]
    else
        print("There was an error retrieving data")
        warn(mainData)
    end

Try this

Datastore will only work if your game has "Enable Studio Access to API Services" enabled. If you try to use datastore in ROBLOX Studio, that is. Now if you test your script in the ROBLOX Player, then your script should work. That is, unless your script is incorrect (which is doesn't look like it).

2 comments

0

I have enabled access to studio API services because if I didn't I would get error 403

0

Ok, try this tutorial: https://youtu.be/DkYupSBUpes I'm saying this because I can't find anything wrong with your code

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