Lua: set each new table element to default

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) 
+7
lua-table lua hash
source share
2 answers

You can set the __index __index to counter to return 0:

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

but it is simpler and more understandable:

 counter[subs] = (counter[subs] or 0) + 1 
+7
source share

The lhf solution is enough for your case. For completeness, I would like to mention that there is a more complex way that allows somewhat more complex functionality. In particular, it acts “as expected” when you use it with mutable values, such as a table: it simultaneously creates an element and assigns it to the key when it is created.

 function defaultTable(constructor) local new = {} local function initIndex(key) local value = constructor() new[key] = value return value end setmetatable(new, {__index=initIndex}) return new end 
0
source share

All Articles