3

I have a table in Lua:

p = {'sachin', 'sachin', 'dravid', 'Dhoni', 'yuvraj', 'kohli'}

I want to count frequency of each name in table .

test1 = {sachin=2, dravid=1, Dhoni=1, yuvraj=1, kohli=1}

I tried this program with lot of for loops .Please see my code

> function exec(ele,p)
count = 0
for k,v in pairs(p) do
if ele == p[k] then
count = count +1 
end
end
return count
end


> new_table = {}
> for k,v in pairs(p) do
new_table[v] = exec(v,p)
end
> 
> for k,v in pairs(new_table) do
print(k,v)
end
dhone   1
yuvraj  1
kohli   1
sachin  2
dravid  1

I want to do this more efficient way. How can I achieve this?

2 Answers 2

5

You can count the frequency like this:

function tally(t)
  local freq = {}
  for _, v in ipairs(t) do
    freq[v] = (freq[v] or 0) + 1
  end
  return freq
end

And here's another demo example.

Sign up to request clarification or add additional context in comments.

Comments

1

Using metatable may be a little unnecessary for this simple case, just showing another option:

local mt = {__index = function() return 0 end}
local newtable = {}
setmetatable(newtable, mt)

for _, v in pairs(p) do
    newtable[v] = newtable[v] + 1
end

The metamethod __index above gives the table 0 as the default value.

1 Comment

@ms2008vip Ah yes, I tested with the name t, but when posted here, I noticed OP used the name newtable, so I changed it accordingly, apparently I missed one. Fixed, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.