Combine two tables including a multiple count

Posted by Blainer on Tue 30 Jun 2009 05:45 PM — 3 posts, 18,164 views.

#0
I can't for the life of me figure out how to do this.

I'm building an inventory table from the wildcards table returned from a trigger. I want to insert the wildcards table into the inventory table only if it's unique and add a quantity field at position 0, if it's not I want to add 1 to the quantity field.

This is what I have so far:

wildcards[0] = nil
if #invTcache == 0 then
	table.insert (invTcache, wildcards)
	invTcache[1][0] = 1
else
	t = invTcache
	for i,v in pairs (t) do
		if v[3] == wildcards[3] then
			invTcache[i][0] = invTcache[i][0] + 1
		else
			table.insert (invTcache, wildcards)
			invTcache[i][0] = 1
		end
	end
end


Wildcard table:
1="159820476"
2=""
3="a @Wsugar @Ycoated @Cdonut@w"
4="0"
5="14"
6="0"
7="-1"
8="-1"
1="157482523"
2=""
3="a water flask"
4="0"
5="12"
6="0"
7="-1"
8="-1"

What I want to finish with:
1:
1="159820476"
2=""
3="a @Wsugar @Ycoated @Cdonut@w"
4="0"
5="14"
6="0"
7="-1"
8="-1"
0="1" <<--- item count
2:
1="157482523"
2=""
3="a water flask"
4="0"
5="12"
6="0"
7="-1"
8="-1"
0="2" <<--- item count

Thank you
#1
Try something like this:


wildcards[0] = nil
if #invTcache == 0 then
    table.insert (invTcache, wildcards)
    invTcache[1][0] = 1
else
    t = invTcache
    found = false
    -- search for match, change found to true if we find one
    for k,v in pairs (t) do
      if v[3] == wildcards[3] then
        found = true
        invTcache[k][0] = invTcache[k][0] + 1
      end
    end
    if not found then
      wildcards[0] = 1
      table.insert (invTcache, wildcards)   
    end
end
Amended on Tue 30 Jun 2009 06:17 PM by Bast
#2
Thanks