Attempt to index nil with 'Items' (Table error)

This is my current table:

	if not Inventory then
		Inventory = {
			["Items"] = {

			}
		}
	end
	inventories[Player] = Inventory

This is what i’m trying to do:

table.insert(inventories[Player]["Items"],itemData)

I am getting this unusual error that suddenly happened, I tried undoing any changes, but it just seemed to happen.

-- That's the error.
ServerScriptService.Modules.InventoryModule:40: attempt to index nil with 'Items'
1 Like

When are you inserting? Is it after you do inventories[Player] = Inventory?

Yes, I fire that once I click on a click detector.

Could you show the whole script? I’m having a hard time understanding. It could be you’re trying to insert too early.

So once a player joins they have a table created:

invmod:CreateInventory(plr)

This is my Click Detector event:

workspace.AddItem.ClickDetector.MouseClick:Connect(function(plr)
	invmod:AddItem(plr,{
		Name = "Wand",
		Type  = "Magic Weapon",
		State = "Unequipped",
		Slot = 0;
		UniqueID = nil
	})
end)

This is my ‘general’ module script:

local inventories = {} 

function inventoryHandler:CreateInventory(Player, Inventory)
	if not Inventory then
		Inventory = {
			["Items"] = {

			}
		}
	end
	inventories[Player] = Inventory
	return inventories[Player]
end

function inventoryHandler:AddItem(Player, itemData)
	local inventory = inventories[Player]
	if itemData then
		table.insert(inventories[Player]["Items"],itemData)
		reps.Events.InventoryInfo:FireClient(Player,inventory)
	end
	return true
end

If inventories[Player] is nil, that means CreateInventory was never called for that specific player. In AddItem, add print(Player, inventories[Player]) and if any of those are not what you expect, you’ll know your problem.

1 Like

It actually fires this:

  Korrow table: 0x26751b325e7f2439

That should mean everything is fine (for that specific player). There’s no way you’d get attempt to index nil with 'Items' if inventories[Player] is not nil :slight_smile:

1 Like

I have no idea what has happened but suddenly it does not happen o-o… As I said I have done nothing

and now it just fixed randomly…

1 Like

I had this problem too with my inventory system when un-equipping and equipping. The way I solved it was by doing this:

function AddItem(player, itemData)
      local inventory = inventories[player.UserId]
      local items = tableClone(inventory["Items"])
      if itemData ~= nil then
            items[GetAmountInTable(items) + 1] = itemData
             inventories[player.UserId]["Items"] = items
      end
end

function TableClone(tbl)
	local returnTable = {}
	for index, value in pairs(tbl) do
		if type(value) ~= "table" then
			returnTable[index] = value
		else
			returnTable[index] = TableClone(value)
		end
	end
	return returnTable
end

function GetAmountInTable(tbl)
      local count = 0
      for index, value in pairs(tbl) do
            count = count + 1
      end
      return count
end
1 Like