On 12/13/2012 01:02 PM, Jerome Vuarand wrote:
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
Wouldn't this be non-reentrant should the called userdata itself call gsub()
[or cause it to be called via loaded script]? ref[1] would now be the inner
gsub()'s repl, and when the outer gsub() finds another match it will call
unref() again which will dereference to the wrong repl.