Carpetsmoker February 2016

Get the first value from an iterator

I would like to split a string by a separator and get only the last part. I don't care about the rest. I know I can do:

local last
for p in string.gmatch('file_name_test', '_%w+$') do last = p end

Which works, but is, IMHO, ugly.

Is there a more elegant way to just say:

local last = string.gmatch('file_name_test', '_%w+$')[1]

Which doesn't work because gmatch returns an iterator (and not a table).

Answers


Nick Gammon February 2016

Use string.match which is not an iterator:

local last = string.match('file_name_test', '_(%w+)$')
print (last)  --> test


Nicol Bolas February 2016

The pattern _%w+$ will only ever return a single match. That's because you anchored it at the end of the string, so it can only either match or fail to match (if there isn't an underscore followed by at least one %w character at the end).

The g* series of pattern matching are for iterating over a sequence of matches. If you want all the matches all at once (returned as multiple return values), use the non-g-prefixed functions. Like string.match:

string.match('file_name_test', '_%w+$')

If there is no match, then you'll get nil back.


warspyking February 2016

Although the other answers do give you a correct answer for your situation, I am going to propose an answer to your question. Which was to get the first item from an iterator.

And the answer is actually quite simple. Since an iterator is just something that continues to return until it returns nil, we just have to call it!

local first = string.gmatch('file_name_test', '_%w+$')()

I am quite confused however, because in your question you also ask about the last thing it will return. I'm sad to say you cannot do this without iterating over them all, because an iterator cannot "jump ahead".

Post Status

Asked in February 2016
Viewed 2,155 times
Voted 13
Answered 3 times

Search




Leave an answer