2

I try to group values in a double dimension table in an other table, but without duplicates. All attempts i made create a table with duplicates.

Here's an example:

This is my table:

tab1 = {
       {id = "id1", dmg = 0, qty = 1},
       {id = "id2", dmg = 0, qty = 1},
       {id = "id3", dmg = 0, qty = 1},
       {id = "id1", dmg = 0, qty = 1},
       }

and i would like an other table like that:

tab2 = {
       {id = "id1", dmg = 0, qty = 2},
       {id = "id2", dmg = 0, qty = 1},
       {id = "id3", dmg = 0, qty = 1},
       }

So i want my qty values to be summed and tables to be groupe like in the example. Does Someone have an idea for this problem ? Is there a function to do this ?

Thanks for your answers. Sorry if my english is bad, it's not my native language.

aquilon
  • 31
  • 3

2 Answers2

1

There is no builtin function for this. You have to write your own. Here is my take.

tab1 = {
       {id = "id1", dmg = 0, qty = 1},
       {id = "id2", dmg = 0, qty = 1},
       {id = "id3", dmg = 0, qty = 1},
       {id = "id1", dmg = 0, qty = 1},
}

local a={}
for k,v in ipairs(tab1) do
    local id=v.id
    if a[v.id]==nil then
        a[v.id] = { id=v.id, dmg=v.dmg, qty=v.qty }
    else
        a[v.id].qty=a[v.id].qty+v.qty
    end
end

local tab2={}
local n=0
for k,v in pairs(a) do
    n=n+1
    tab2[n]=v
end
table.sort(tab2, function (a,b) return a.id < b.id end)

for k,v in ipairs(tab2) do
    print(k,v.id,v.dmg,v.qty)
end
lhf
  • 70,581
  • 9
  • 108
  • 149
0

Here's one possibility. (I assume your unique key is just id. If not, adjust accordingly. Also, I only add qty, you may need to also add dmg.)

tab1 = {
       {id = "id1", dmg = 0, qty = 1},
       {id = "id2", dmg = 0, qty = 1},
       {id = "id3", dmg = 0, qty = 1},
       {id = "id1", dmg = 0, qty = 1},
       }

function tablecopy(t)
  local ans = {}
  for k,v in pairs(t) do
    ans[k] = v
  end
  return ans
end

function nodups(t)
  local temp = {} --workspace

  for _,t in ipairs(t) do
    if temp[t.id] == nil then
      temp[t.id] = tablecopy(t)
    else
      temp[t.id].qty = temp[t.id].qty + t.qty
      --temp[t.id].dmg = temp[t.id].dmg + t.dmg
    end
  end

  -- and, if you need to convert to array
  local t = {}
  for _,v in pairs(temp) do
    t[#t+1] = v
  end

  return t
end

tab2 = nodups(tab1)
tonypdmtr
  • 3,037
  • 2
  • 17
  • 29