Script checks if data is not nil, but still throws out an error

I added datastores to my game, and when I joined the game it returned with this error:

What I’m confused about is why this errors when it checks if the data is not nil on the line before.

players.PlayerAdded:Connect(function(plr)
	-- leaderstats
	leaderstats = servStorage.leaderstats
	leaderstats.Parent = plr
	
	--loading data
	
	-- Inventory Data
	local success, inventoryData = pcall(function()
		return invStore:GetAsync(plr.UserId)
	end)
	
	if success then
		if inventoryData ~= nil then
			for i, v in pairs(inventoryData["Ore"]) do -- this is the line with the error
				leaderstats.Ore[i].Value = v
			end
			for i, v in pairs(inventoryData["Materials"]) do
				leaderstats.Materials[i].Value = v
			end
		end
	end
	
	-- Leaderstat Data
	local success, leaderstatData = pcall(function()
		return invStore:GetAsync(plr.UserId)
	end)

	if success then
		if leaderstatData ~= nil then
			for i, v in pairs(leaderstatData) do
				leaderstats[i].Value = v
			end
		end
	end
	
end)

You did check the root table inventoryData but you actually didn’t check if the indexes of the inventoryData are present or not.

You should add a second and third criteria to your statement that includes the inventoryData["Ore"] and inventoryData["Materials"].

if inventoryData ~= nil and inventoryData["Ore"] and inventoryData["Materials"] then
1 Like

But the thing is, one of them might be nil while the other one may be not. How can I check that at least one of them isnt nil?

Edit: I get it now.

You have the option to split that if statement if needed so that, every for loop is wrapped by a single statement.

if inventoryData ~= nil then
    if inventoryData["Ore"] then
        for i, v in pairs(inventoryData["Ore"]) do
            leaderstats.Ore[i].Value = v
        end
    end
    if inventoryData["Materials"] then
        for i, v in pairs(inventoryData["Materials"]) do
            leaderstats.Materials[i].Value = v
        end
    end
end

Alright, nice to hear that.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.