lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi.

I was surprised to discover that gfind does not honour the "^" anchoring
symbol (which I thought would mean start the scan where it was left off).
The naive implementation of gfind with find would honour the anchor,
because find interprets ^ as meaning anchor to the declared start of the
scan, not anchor to the beginning of the string, and in fact what I did was
replace the call to gfind with an equivalent generator using find. However,
it would be very little work to add this capability to gfind, and I don't
believe that any other interpretation of "^" makes any sense in this
context.

What I was trying to do, to show the utility of the feature, was decompose
a sequence of whitespace separated words. The way I used to do this with
gsub was to use a functional replacement which did something with the word
and then returned the empty string instead of nil; then I could check the
result of the substitution and see if anything had not been matched. But
that is a bit clumsy and leads to delayed error checking; also, it is nicer
to be able to write things in a for loop sometimes. So I thought I could do
something like this:

function process_words(str)
  local error_position = 0
  for word, n in string.gfind(str, "^%s*(%w+)%s*()") do
    error_position = n
    -- do something with word
  end
  if error_position ~= string.length(str) then
    -- there was an error at character error_position+1
  end
end

But of course it didn't work.

It's not critical; using an iterator based on string.find works just fine
for me. I just thought it was odd.

Rici