I want to get the most commonly used k-size substring in a string. To do this, I use a table to store the number of occurrences for each substring. Here is 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 value counter[subs] = (counter[subs] ? counter[subs]+1 : 1) . This line will only be counter[subs] = counter[subs] + 1 if we can set each new counter element with 0 . Is this possible in Lua? If not, what's the best way to do something like this?
For example, in Ruby, this is done by declaring a hash as follows:
counter = Hash.new(0)
lua-table lua hash
Fábio perez
source share