Help with counting the amount of a specific item in table

Hello, I have a table which adds a item every time i pick up a specific item. When I pick up multiple of that item it adds the item to the table again but it looks like:

Inventory{
  [1] = Sword,
  [2] = Sword
}

How can I write some code that counts how many are in this table?

2 Likes

#Inventory

1 Like

If its a table you just do

print(#table)

However, as I think if it is a dictionary you would do something like this

local function getLengthOfDictionary(tab)
  local sum = 0
  for _,_ in pairs(tab) do
    sum += 1
  end
  return sum
end

print(getLengthOfDictionary(table))
1 Like

Hello, I ran into some issues when using this in my system because when I pick up a different item it just stacks it up but if I pick up the same item all those stacked up points go into that item.

local _amt
local function getLengthOfDictionary(tab)
	local sum = 0
	for _,_ in pairs(tab) do
		sum += 1
		_amt = sum
	end
	return sum
end


local function AddItem(Inv, item)
	
	local itemType = ItemModule[item.Name]["Type"]
	
	getLengthOfDictionary(Inventory[itemType])
	for counter = 1,20 do
		local slot = Inv:WaitForChild("Slot"..counter)
		if slot.Val.Value == "" then
			slot.Val.Value = tostring(item)
			slot.Amount.Text = _amt
			break
		elseif slot.Val.Value == item.Name then
			slot.Amount.Text = _amt
		else
			return false
		end
		return true
	end
end

1 Like