Simon04090
Simon04090

Reputation: 371

Count number of occurrences of a value in Lua table

Basically what I want to do is convert a table of this format

result={{id="abcd",dmg=1},{id="abcd",dmg=1},{id="abcd",dmg=1}}

to a table of this format:

result={{id="abcd",dmg=1, qty=3}}

so I need to know how many times does {id="abcd",dmg=1} occur in the table. Does anybody know a better way of doing this than just nested for loops?

Upvotes: 3

Views: 1771

Answers (2)

warspyking
warspyking

Reputation: 3113

So you want to clear duplicate contents, although a better solution is to not let dupe contents in, here you go:

function Originals(parent)
    local originals = {}
    for i,object in ipairs(parent) do
        for ii,orig in ipairs(originals) do
            local dupe = true
            for key, val in pairs(object) do
                if val ~= orig[key] then
                    dupe = false
                    break
                end
            end
            if not dupe then
                originals[#originals+1] = object
        end
    end
    return originals
end

I tried to make the code self explanatory, but the general idea is that it loops through and puts all the objects with new contents aside, and returns them after.

Warning: Code Untested

Upvotes: 0

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

result={{id="abcd",dmg=1},{id="defg",dmg=2},{id="abcd",dmg=1},{id="abcd",dmg=1}}

local t, old_result = {}, result
result = {} 
for _, v in ipairs(old_result) do
  local h = v.id..'\0'..v.dmg
  v = t[h] or table.insert(result, v) or v
  t[h], v.qty = v, (v.qty or 0) + 1
end

-- result: {{id="abcd",dmg=1,qty=3},{id="defg",dmg=2,qty=1}}

Upvotes: 5

Related Questions