Why is this simple loop skipping?

Hi Guys, so I made a simple loop that loops through a table but for some reason, it skips it.

Code -

function Inventory:AddItem(Item, amount)
	for i, v in pairs(self) do
		if v.isOccupied == false then
			print(i)
			v.isOccupied = true
			v.item = Item
			break
		end
	end

self (the table) has 3 values but it’s skipping the 2nd one. Those 3 tables inside self are -

["1"] = {
			isOccupied = false, -- checks if the slot is occupied
			item = nil, -- what item is inside the slot
			amount = 0
		},
		["2"] = {
			isOccupied = false, -- checks if the slot is occupied
			item = nil, -- what item is inside the slot
			amount = 0
		},
		["3"] = {
			isOccupied = false, -- checks if the slot is occupied
			item = nil, -- what item is inside the slot
			amount = 0
		}
	}

Any help is appreciated, thanks :slight_smile:

I’m assuming if they already have the item you add the amount to their current amount of that item.
And if they don’t have it then insert a slot for that item using table.insert

local PlayerInventory = {
	
};

function AddItem(Item, amount)
	local occupiedIndex = nil
	
	for i, v in pairs(PlayerInventory) do
		if v.item == Item then
			occupiedIndex = i
		end
	end
	
	if occupiedIndex == nil then
		table.insert(PlayerInventory, {
			isOccupied = true,
			item = Item,
			amount = amount
		})
	elseif occupiedIndex ~= nil then
		PlayerInventory[occupiedIndex].amount += amount
	end
end
1 Like

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