It's actually pretty simple.
string.gsub will take the second parameter as a regular expression and search through the string you provided it, recording all matches. The reason (%w+) (which matches any word) works over an entire string is because it doesn't contain 'open line'/'end line' (^/$) characters.
In our case, the third argument is a function (albeit an anonymous one), so that all matches from the string are parsed to that. Now the reason we needed to nest table.insert is because it takes two parameters -- the first being the table (variable) to add onto, and the second the actual string. I used an anonymous function (which is just a temporary function that gets 'deleted' after wards) here, as it's really the only place you'll be using it, and it makes things much less complicated.
You could also have a more general function like this:
Code: Select all
function multiAdd(tbl, string1)
string.gsub(string1, "(%w+)", function(string2) if type(tbl) == "table" then table.insert(tbl, string2) end end)
end
That could be used to add any amount of words (separated by punctuation, whitespace, etc) to any table as long as it already exists. The if just checks to see if tbl is really a table.
You can get more complicated with gsub if you want, see that link in my last post.