Search code examples
arraysstringlualua-patterns

Store Lua string.match output to array


Normally I use two variables to store the output of something like this:

a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
k, v = string.match(a[1], 'alarm dentist (%w+) (%w+)' )
print(k, v)
elephant fabulous

but instead of using two variables I would like to store it in an array or table.

My final goal is to create a function where I input an array (which in this case is 'a') and a pattern (which is this case is 'alarm dentist (%w+) (%w+)') and that it returns the desired accompanying word/s if found or 'nil' otherwise. The catch is that the number of word that the pattern looks for is undefined. In this case is 2 but I want the user to be able to input any pattern, i.e. 'alarm dentist (%w+) (%w+) (%w+) (%w+)' or 'alarm dentist (%w+)'.

So this was my line of thought so far: (I'm using the command line tool in Ubuntu 12.04LTS to test it)

a = {'alarm boy car dentist','alarm car dentist elephant','alarm dentist elephant fabulous','alarm elephant fabulous goat'}
function parse_strings (array, pattern)
words = nil
for i=1, #array do
    c = string.match(array[i], pattern)
    if c ~= nil then
        words = c
        end
    end
    return words
end
print (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
elephant

but only the first value is stored in "c" instead of c[1]='elephant' and c[2]='fabulous'.

Worst case I could search for how many words the pattern is searching for but I would still need to find a way to store the undefined size output from string.match in one array.


Solution

  • You can store the result into a table:

    local t = {string.match(array[i], pattern)}
    if #t ~= 0 then
        words = t
        end
    end
    

    The return value of parse_string is a table now:

    local result =  (parse_strings (a, 'alarm dentist (%w+) (%w+)'))
    for k, v in ipairs(result) do
        print(k, v)
    end