apnix-uk
apnix-uk

Reputation: 13

Why does this Lua code return an index?

I found this Lua in an answer by lhf to a question on finding the index of the last occurrence of a string (needle) in another string (haystack)....

function findLast(haystack, needle)
  local i=haystack:match(".*"..needle.."()")
  if i==nil then return nil else return i-1 end
end
s='my.string.here.'
print(findLast(s,"%."))
print(findLast(s,"e"))

You'd think I'd be happy to have found the answer I wanted to my original question but I'm afraid I like to know not only that the answer works (and it does work for all inputs I tried) but why it works ;-)

The trouble is I can't find any Lua documentation which states the behaviour for s:match returning an index within a string when the capture does not define a pattern.

Can anyone point me in the direction of something which confirms this is defined and expected behaviour and not just a nice coincidence that it happens to work?

Upvotes: 1

Views: 62

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80921

This is in the manual. The section on Patterns

As a special case, the empty capture () captures the current string position (a number). For instance, if we apply the pattern "()aa()" on the string "flaaap", there will be two captures: 3 and 5.

Upvotes: 2

Related Questions