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

Attempt to index nil with "Bucks"?

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)

2 comments

1

Could you provide a snippet of the :SetAsync() part?

0

@Hypoxla i just edited it to show the part where data is saved. :SetAsync() is on line 13 of the 2nd code block

1 answer

✓ Accepted answer

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"]

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