Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: set every new element in table to a default value

I want to get the most frequent k-sized substring in a string. To achieve this, I'm using a table to store the number of occurrences for each substring. Here's the code:

function frequentWords(seq, k)
  local subs = ""
  local counter = {}
  for i = 1,(seq:len()-k+1) do
    subs = seq:sub(i, i+k-1)
    counter[subs] = (counter[subs] and counter[subs] + 1 or 1)
    --print(subs .. ": " .. counter[subs])
  end
end

The line counter[subs] = (counter[subs] and counter[subs] + 1 or 1) has the same mean of counter[subs] = (counter[subs] ? counter[subs]+1 : 1). This line would be only counter[subs] = counter[subs] + 1 if we could set every new counter element with 0. Is this possible in Lua? If not, what's the best way of doing something similar?

For instance, in Ruby, this is done by declaring a Hash like this:

counter = Hash.new(0)
like image 563
Fábio Perez Avatar asked Nov 05 '13 11:11

Fábio Perez


1 Answers

You can set an __index metamethod in counter to return 0:

setmetatable(counter,{__index=function () return 0 end})

but this is easier and clearer:

counter[subs] = (counter[subs] or 0) + 1
like image 120
lhf Avatar answered Nov 15 '22 22:11

lhf