Trouble indexing through a table

I have two bricks in workspace and when I click one of them they are supposed to be inserted into a table, and If the player already has the item it will just increase their quantity.

It works perfectly if they click the item 1 first and then the second but if I click the second item first it will error. My guess is that it’s not iterating through the entire table.

 ReplicatedStorage.InventorySystem:26: attempt to index field '?' (a nil value)

the script

	        local InventorySystem = {}
		
		InventorySystem.Items = {
			[1] = {Name = "Axe", Quantity = 1},
			[2] = {Name = "Pickaxe", Quantity = 1},
		}
		
		InventorySystem.Inventories = {}
		
		InventorySystem.CreateInventory = function(player)
			InventorySystem.Inventories[player.Name] = {}
			
			print("//Created a table for " .. player.Name)
		end
		
		InventorySystem.AddItemInventory = function(player, Item)
			local id
			for i,v in ipairs(InventorySystem.Items) do
				if Item.Name == v.Name then
					id = i
					if InventorySystem.Inventories[player.Name][id] then
						InventorySystem.Inventories[player.Name][id].Quantity = InventorySystem.Inventories[player.Name][id].Quantity + 1
						
						print(InventorySystem.Inventories[player.Name][id].Name .. InventorySystem.Inventories[player.Name][id].Quantity)
					else
						table.insert(InventorySystem.Inventories[player.Name], InventorySystem.Items[id])
						
						print("//Added " .. InventorySystem.Inventories[player.Name][id].Name .. " to " .. player.Name .. "inventory")
					end
				end
			end
		end
		
	return InventorySystem
1 Like

That is not the issue, a.b is syntactic sugar (a nicer way to write something) for a["b"].

1 Like

You are Totally Correct!, Forgot you can write it that way (used to my habits)

Ok, so i did some testing i think i know the problem, essentially the reason picking the second item first gives you a error is because here:

print("//Added " .. InventorySystem.Inventories[player.Name][id].Name .. " to " .. player.Name .. "inventory")

id is equal to 2 which means you are trying to get the second value of the array which ultimately does not exist because instead of adding the inventory item in the second index of InventorySystem.Inventories[player.Name] you are adding it as the first value in the array

So if you did want to use the id to index a item in your inventory items you would want to change this:

table.insert(InventorySystem.Inventories[player.Name], InventorySystem.Items[id])

To something like this:

InventorySystem.Inventories[player.Name][id]  = inventorySystem.Items[id] 

However if you wanted this to be added in order in respect of their id as and index in the array , you could do this is something similar to this:

table.insert(InventorySystem.Inventories[player.Name], id,  InventorySystem.Items[id])
2 Likes