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

Attempt to index nil with "Bucks"?

Asked by
CodeWon 181
2 years ago
Edited 2 years ago

My data store is getting an error upon trying to load a player's data, here is the script:

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

local inGame = 0

game.Players.PlayerAdded:Connect(function(player)

    inGame = inGame + 1

    -- Leaderstats

    local leaderstats = Instance.new("Folder",player)
    leaderstats.Name = "leaderstats"

    local Bucks = Instance.new("IntValue",leaderstats)
    Bucks.Name = "Bucks"

    -- Data

    local key = "Player_"..player.UserId -- The key is where the data is stored 

    local data
    local succes, errorMessage = pcall(function()
        data = gameData:GetAsync(key) -- gameData:GetAsync(key) finds the data stored under the players key
    end)

    if succes then
        -- If the pcall above is successful, the players data will be loaded
        Bucks.Value = data.Bucks
    end
end)

The data saves when a player leaves, but there is an error when the player joins

Edit of when the data is saved:

function saveData(plr) -- This will be called when player leaves

    inGame = inGame - 1

    local key = "Player_"..plr.UserId

    local data = { 
        -- Everything in this table is what will be saved
        Bucks = plr.leaderstats.Bucks.Value;
    }

    local success, errorMessage = pcall(function()
        gameData:SetAsync(key, data) -- gameData:SetAsync(key, data) sets the data under the players key to the current data
    end)

    if success then
        print("Saved data for "..plr.Name.."/"..key)
    else
        print("Error saving data for "..plr.Name.."/"..key)
        warn(errorMessage)
    end
end

game.Players.PlayerRemoving:Connect(function(player)
    saveData(player)
end)

game:BindToClose(function()
    -- game:BindToClose() detects when the server is shutdown, the code below will run on server shutdown
    -- If the server shutsdown, all the player's data needs to be saved
    for _, player in pairs(game.Players:GetChildren()) do
        saveData(player)
    end
end)
1
Could you provide a snippet of the :SetAsync() part? Hypoxla 125 — 2y
0
@Hypoxla i just edited it to show the part where data is saved. :SetAsync() is on line 13 of the 2nd code block CodeWon 181 — 2y

1 answer

Log in to vote
1
Answered by
Hypoxla 125
2 years ago

I took a look at your script, and it appears that data returns a table.

To fix your script, replace Line 29 with this:

 Bucks.Value = data["Bucks"]

Ad

Answer this question