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

[ANSWERED] How to fix "attempted to index local 'player' (a nil value)"?

Asked by
sssynk 58
4 years ago
Edited 4 years ago

I am making a leaderstats script with DataStores, and whenever I leave the game, the script throws an error, "attempted to index local 'player' (a nil value)". I have seen the forum posts throughout scripting helpers and other websites detailing how to fix this. I have tried these, and they work, but the players' data needs to save for the next time they join. We need the player to not be a nil value to save the data. How to fix? Thanks in advance! :D

The error occurs at line 32, and is later thrown to the console by line 39.

Code:

local DataStore = game:GetService("DataStoreService")
local ds = DataStore:GetDataStore("PointsData")

print("started")

game.Players.PlayerAdded:Connect(function(player)
 local leaderstats = Instance.new("Folder", player)
 leaderstats.Name = "leaderstats"

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

 local data
 local success, errormessage = pcall(function()
    data = ds:GetAsync(player.UserId.."-points")
end)

 if success then
    print("got data")
    points.Value = data
else
    print("could not get data")
    warn(errormessage)
end

end)


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

    local success, errormessage = pcall(function(player)
        ds:SetAsync(player.UserId.."-points",player.leaderstats.Points.Value)
    end)

    if success then
        print("Points saved successfully.")
    else
        print("Error saving data.")
        warn(errormessage)
    end

end)

1 answer

Log in to vote
0
Answered by
sssynk 58
4 years ago
Edited 4 years ago

My bad. I added a "player" variable to the pcall function on line 31. Thanks everyone!

0
yay good job royaltoe 5144 — 4y
Ad

Answer this question