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

[SOLVED] How do I fix "attempt to get length of local 'Data' (a nil value)"?

Hi! When I'm using data stores I am having a problem. When I get the data by using a key and then check how many objects are in the table I get this error.

attempt to get length of local 'Data' (a nil value)

I know that this means that when it attempts to get the length of the table known as "Data" it finds that "Data" is a nil value. Meaning it's not existent. Although, the problem that lies here is that the table does exist and it is a value. Here's my server script.

local DataStore = game:GetService("DataStoreService"):GetDataStore("TimeSlots")
local Event = game.ReplicatedStorage:FindFirstChild("PlayerData")
local PublicData = {}

game.Players.PlayerAdded:connect(function(player)
	local Data = {}
	local PublicData = DataStore:GetAsync("Public")
	
	if PublicData then
		Data = PublicData
		PublicData["Public"] = Data
	else
		local ToSave = {{Day = "Sunday", Time = "3:00PM EDT", Host = "thebootsie123"}, {Day = "Monday", Time = "4:21PM EDT", Host = "thebootsie123"}}
		
		PublicData["Public"] = ToSave
		DataStore:SetAsync("Public", ToSave)
	end
	
	print(#PublicData["Public"])
end)

game.Players.PlayerRemoving:connect(function(player)
	if player:GetRankInGroup(3272666) >= 14 then
		SessionData[player] = nil
	end
	
	PublicData["Public"] = nil
end)

local function EventFunc(player, Mode)
	if Mode == "GetDataPlayer" then
		return SessionData[player]
	elseif Mode == "GetDataPublic" then
		local Thing = PublicData["Public"]
		return Thing
	end
end

Event.OnServerInvoke = EventFunc

As you can see here in the server script I am printing out the length of the table. In this part of the script, I don't get that error and it prints out the correct length. But in the remote function when I return the "PublicData" table which is the table it just printed the length of, it gives the error. Here is the part in the local script.

	local Data = game.ReplicatedStorage.PlayerData:InvokeServer("GetDataPublic")

	if #Data >= 1 then

	end

As you can see it's very straight forward. When it hits the line if #Data >= 1 then I then get the error.

attempt to get length of local 'Data' (a nil value)

Anyone know why this is happening?

1 answer

I found the answer. I had to replace local PublicData = DataStore:GetAsync("Public") with PublicData = DataStore:GetAsync("Public"). I apparently didn't see that I declared two variables with the same name.

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