String.match / String.find

Posted by Scripts on Sun 23 Sep 2007 12:20 AM — 3 posts, 14,356 views.

#0
is there any way to dump the result of this directly into an array or a table?

i.e.

array={}
SomeTableElement={
"^(.+) searching for 2 (.+) matches here%.",
"^only searching for 1 (+.) here%."
}

for i=1,2 do
array = string.match(aString, SomeTableElement[i])
--do something with array here
end

I am trying to make a flexible string search that bases itself on valus in a table, but I can't seem to create a universal way to store all the data coming out of the string.match() function.

I'm extremely new to LUA and any help is greatly appreciated.

Amended on Sun 23 Sep 2007 03:37 AM by Scripts
Australia Forum Administrator #1
Yes you can, but I wonder what you are really trying to do here.

Since string.match can return multiple results, and you want to store them somewhere, you can make a table on-the-fly like this:


for i=1,2 do
  array = { string.match(aString, SomeTableElement[i]) }
  --do something with array here
end


Note the { ... } here which puts the string.match results into a table, which is then stored in "array".

The first thing I would do is change it from using "for i=1,2 do" to using ipairs, because I assume you will gradually add more items to the table, and don't want to have to keep remembering to change the 2 to 3, and then 4 and so on. This code will do the same thing, for any size table:


for k, v in ipairs (SomeTableElement) do
  array = { string.match(aString, v) }
  --do something with array here
end


I use the variables k and v to represent the Key and Value for the table. The key will simply be 1, 2, 3 ... and so on, and the value is the table item value for each key.

The other thing I worry about here is that you are applying the search to the same string, regardless of whether or not you get a match.

If the matches are mutually exclusive you might want to break out of the loop as soon as a match is made.
#2
Ahh, that's how you do it.

In my current code I do use ipairs(), and I have a test case for matching strings...just couldn't figure out how to put the data into a table. Eventually I want to use a lookup table to re-order the string.match() results for each case individually, but this gets me rolling again.

Thanks Nick, you're the man :)