How to check if there are duplicates in the table

Hello everyone, I’m making a crafting dictionary. Some items need multiple other items to craft, and these are all stored in a dictionary. Example:

local OtherReq = {
   ["Book"] = {"WolfFur","WolfFur","WolfFur","WolfFur","String","String","String","String",},
   ["Pumpkin"] = {"PumpkinFood","PumpkinFood","PumpkinFood","PumpkinFood","PumpkinFood",},
}

And then, it adds each string in the list onto the description:

for countt = 1, #OtherReq[CraftableList[count]] do
	Text.Text = Text.Text..",\n "..OtherReq[CraftableList[count]][countt]
end

However, it ends up looking really weird like this:
image
Instead, I would want it to show something like
FurHat
CraftingTable is Required
Fire is Not Required
Wood: 0
Stone: 0
Gold: 0
Diamond: 0
4x WolfFur
2x String

How would I do this?

Could you store your requirements as counts instead of measuring duplicates?

local OtherReq = {
  ["Book"] = {
    WolfFur = 4,
    String = 4
  },
  ["Pumpkin"] = {
    PumpkinFood = 5
  },
}

Then it’s pretty simple to figure out how much of each item you need:

for item, amount in pairs(OtherReq["Book"]) do
  print(string.format("%dx %s", amount, item))
end

You could also store as a list of {"name", amount} pairs, if you need to maintain ordering.


Otherwise you’d have to build that table yourself anyways:

local function GetCounts(tab)
  local counts = {}
  for _, item in ipairs(tab) do
    local c = counts[item]
    counts[item] = c and c + 1 or 1
  end
  return counts
end

for item, amount in pairs(GetCounts(OtherReq["Book"])) do
  print(string.format("%dx %s", amount, item))
end

which just seems like unnecessary extra steps if you store your data like that in the first place

1 Like