lua-users home
lua-l archive

Re: A Lua 5.2 string pattern issue

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


> I've come across a new error when doing some compatibility tests with
> Lua 5.2 (work2, naturally!)
> 
> -- escape.lua
> -- escape all magic characters except ,ドル which has special meaning
> -- Also, un-escape any characters after ,ドル so $( passes through as is.
> function escape (spec)
> return spec:gsub('[%-%.%+%[%]%(%)%^%%%?%*]','%%%1'):gsub('%$%%(%S)','%$%1')
> end
> print(escape '$({def} $')
> 
> $ lua escape.lua
> $({def} $ 1
> $ lua52 escape.lua
> lua52: escape.lua:2: invalid use of '%' in replacement string
> 
> Clearly something has changed; am I doing anything odd?
In the replacement string, '%' can only be followed by '%' or a digit:
 * http://www.lua.org/manual/5.1/manual.html#pdf-string.gsub
 If repl is a string, then its value is used for replacement. The
 character % works as an escape character: any sequence in repl of the
 form %n, with n between 1 and 9, stands for the value of the n-th
 captured substring (see below). The sequence %0 stands for the whole
 match. The sequence %% stands for a single %.
Your replacement string has a '%$', which has an undefined behavior. Lua
5.1 was more lenient about it.
-- Roberto

AltStyle によって変換されたページ (->オリジナル) /