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:
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".
Asked in February 2016Viewed 2,155 timesVoted 13Answered 3 times