lua-users home
lua-l archive

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

> After some questions were asked on the IRC channel, I realized that
> contrary to string.match, string.gsub does not throw an error when
> passed a pattern containing an unfinished capture, ie. an unescaped
> opening parenthesis without the corresponding closing parenthesis. The
> behavior when passing such a pattern is actually quite weird. For
> example calling string.gsub("aaa", "(", "b") returns "bababab", 4.

The behavior is not that weird:

> return string.gsub("aaa", "()", "b")
bababab	4

> return string.gsub("aaa", "", "b")
bababab	4

There are empty strings between all 'a's (as well as before the first
and after the last); these empty strings are replaced by 'b'. (Actually
there are infinite empty strings in those places. But Lua always goes at
least one step ahead after each match.)

So, the only problem is that it does not detect the unfinished capture.
This happens because, unlike string.match, that particular gsub does not
need the capture:

> return string.gsub("aaa", "(", "%1")   -- this one needs the capture
stdin:1: unfinished capture

The "fix" would be to add an explicit check for unfinished captures. I
am not sure it is worth the trouble.

-- Roberto