lua-users home
lua-l archive

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


----- Original Message -----
> On Fri, Apr 13, 2012 at 11:54 AM, Robert Virding
> <robert.virding@erlang-solutions.com> wrote:
> > I am having a bit of trouble comprehending a call to string.gsub in
> > the pm.lua file in thelua-5.2.0 tests. There is a line:
> >
> > assert(string.gsub("abc", "%w", "%1%0") == "aabbcc")
> >
> > which works. My problem is that I don't why the substring %1 works
> > and from where it gets its value. As far as I can see there is no
> > captured substring at all. Using %2 generates an error (as I think
> > it should).
> 
> While I don't particularly like the behaviour, I can form a
> pseudo-explanation as to what is going on. When repl is a table or
> function, and the pattern specifies no captures, then the whole match
> is used as the sole capture. One way of implementing this is to say
> that if a pattern P specifies no captures, then it is treated as (P).
> This effect then spills over to when repl is a string, causing %1 to
> be the whole match.

But isn't that what %0 is for. I have done some more testing and found that if no capture is given in the pattern string then %1 becomes the whole match, while if the pattern contains a capture then that will be used. %2 seems to behave properly

assert(string.gsub("abcd", "%w%w", "%1%0") == "ababcdcd")
assert(string.gsub("abcd", "(%w)%w", "%1%0") == "aabccd")

While I could go and check the C-code I get the feeling that as it is in the tests then it should behave like this, and I can't understand why. There is no mention or example of it in the manual.