Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Getting a nil value from a datastore?

Asked by 4 years ago
Edited 4 years ago
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)

0
On your line "print(MainData)" does it print "nil"? Spjureeedd 385 — 4y
0
yes Barty200 85 — 4y
0
i would assume that it didn't save correctly, because it looks like the loading works fine sheepposu 561 — 4y
0
Yeah maybe the table is not saved as the way it get received. LinavolicaDev 570 — 4y

2 answers

Log in to vote
0
Answered by 4 years ago
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

Ad
Log in to vote
0
Answered by 4 years ago

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).

0
I have enabled access to studio API services because if I didn't I would get error 403 Barty200 85 — 4y
0
Ok, try this tutorial: https://youtu.be/DkYupSBUpes I'm saying this because I can't find anything wrong with your code IAmNotTheReal_MePipe 418 — 4y

Answer this question