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

DataStore giving an error: trying to index nil value?

Hi there! I'm creating a leaderboard on the player list that shows the amount of kills and wins each player has. But when I load into the game, it gives me an error: attempt to index nil value. I don't know what's wrong and all of the tutorials that I watch are outdated. Here is the code:

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("FlipStats")

game.Players.PlayerAdded:Connect(function(Player)
	local Leaderstats = Instance.new("Folder")
	Leaderstats.Name = "leaderstats"
	Leaderstats.Parent = Player
	local Currency = Instance.new("StringValue")
	Currency.Name = "Flips"
	Currency.Value = DataStore:GetAsync(Player.UserId).Flips or 0
	Currency.Parent = Leaderstats
	local Currency = Instance.new("StringValue")
	Currency.Name = "Wins"
	Currency.Value = DataStore:GetAsync(Player.UserId).Wins or 0
	Currency.Parent = Leaderstats
end)

game.Players.PlayerRemoving:Connect(function(Player)
	DataStore:SetAsync(Player.UserId, {
		["Flips"] = Player.leaderstats.Money.Value;
		["Wins"] = Player.leaderstats.Wins.Value;
	})
end)

The error shows up at line 10, where it says Currency.Value = DataStore:GetAsync(Player.UserId).Flips or 0. I expect that if I got past this error, another error would show up at line 14:Currency.Value = DataStore:GetAsync(Player.UserId).Wins or 0.

If someone could help, that would be greatly appreciated! Thanks!

2 comments

0

I despise the "or 0" part, as I did the same thing and it never worked for me. I would set those values as 0. To make things look better, in my opinion, make the 'Currency' variables separate; FlipData and WinData. To grab the data, create a variable "Data", and run pcall function Datastore:GetAsync(Player.UserId). Create an if statement if Success works

0

And overwrite the values (0 as earlier stated) via the Data through Async.

1 answer

✓ Accepted answer

Store the retrieved data in a variable, if it is nil, assign some default value to it Also you should use a pcall here to make sure that if Datastore for whatever reason is not working correctly, your code will not error Example code

local Data
local success, err = pcall(function()
	Data = DataStore:GetAsync(Player.UserId)
end)
if not success then
	print(err) -- not necessary, but helps with debugging
end
if not Data then
	Data = {
		Flips = 0,
		Wins = 0,
	}
end
-- later on
Currency.Value = Data.Flips

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