lua-users home
lua-l archive

Re: string.gsub accepting a callable userdata

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


2012年12月13日 steve donovan <steve.j.donovan@gmail.com>:
> That does work - gsub respects __index, which is nice (I had to check this)
>
> Best global solution in such a situation is the following monkey patch:
>
> local gsub,type = string.gsub,type
>
> function string.gsub(s,pat,repl)
> if type(repl) == 'userdata' then
> local obj = repl
> repl = function(...) return obj(...) end
> end
> return gsub(s,pat,repl)
> end
To avoid the creation of a closure on each call, you can cache one:
local gsub,type = string.gsub,type
local ref = setmetatable({}, {__weak='v'})
local function unref(...) return ref[1](...) end
function string.gsub(s,pat,repl)
 if type(repl) == 'userdata' then
 ref[1] = repl
 repl = unref
 end
 return gsub(s,pat,repl)
end

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