How do I fix the error "attempt to index nil with number"?

I want to make a datastore that saves the player’s text, but I keep receiving the error “attempt to index nil with number”.

I’ve tried getting rid of the data[1]'s “[1]” but it didn’t work.

local dataService = game:GetService("DataStoreService")
local textData = dataService:GetDataStore("textData")

local function saveText(player)
	local StuffToSave = {
		player.PlayerGui:WaitForChild("ScreenGui"):FindFirstChild("TextBox").Text;
	}
	
	local success, err = pcall(function()
		textData:SetAsync(player.UserId, StuffToSave)
	end)
	
	if success then
		print("saved")
	else
		print("couldnt save")
		warn(err)
	end
end

game:GetService("Players").PlayerAdded:Connect(function(player)
	local Gui = player.PlayerGui:WaitForChild("ScreenGui"):FindFirstChild("TextBox")
	
	local data
	local success, err = pcall(function()
		data = textData:GetAsync(player.UserId)
	end)
	
	if success and data[1] ~= nil then
		Gui.Text = data[1]
	else
		print("player doesn't have data lol")
	end
end)

game:GetService("Players").PlayerRemoving:Connect(function(player)
	local success, err = pcall(function()
		saveText(player)
	end)
	
	if success then
		print("saved data")
	else
		print("coudlnt save data")
	end
end)

game:BindToClose(function()
	for index, players in pairs(game:GetService("Players"):GetPlayers()) do
		local success, err = pcall(function()
				saveText(players)
		end)
		
		if success then
			print("saved")
		else
			print("couldnt save")
		end
	end
end)

If you know what I did wrong in here, please help me out. Thank you!

Data is not guaranteed return a table

What do you mean though? Can you please explain a little bit specifically? lol

:GetAsync will only error if there was an issue connecting to the datastore. In the case that the data doesn’t exist, :GetAsync will still be successful, but data will be nil. nil can’t be indexed, so you should just check if data ~= nil before checking data[1].

1 Like

That got rid of the bug, but it still doesn’t work yet :confused:

1 Like

I think it’s because stuff to save is a table
Try data.StuffToSave[1]

game:GetService("Players").PlayerAdded:Connect(function(player)
	local Gui = player.PlayerGui:WaitForChild("ScreenGui"):FindFirstChild("TextBox")
	
	local data
	local success, err = pcall(function()
		data = textData:GetAsync(player.UserId)
	end)
	
	if success and data ~= nil then
         if data.StuffToSave and data.StuffToSave[1] then
		       Gui.Text = data.StuffToSave[1]
         end
	else
		print("player doesn't have data lol")
	end
end)
  1. Is there an error? What is it printing out?

  2. Did you update your code since the OP?