lua-users home
lua-l archive

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


>>>>> "Robert" == Robert McLay <mclay@tacc.utexas.edu> writes:

 Robert> I would like to make calls to io.stderr:write() be silent
 Robert> sometimes but I am unable to redefine that function
 Robert> temporarily. Below is a tiny example of what I tried. This
 Robert> doesn't work. What does?

This intercepts all file:write calls and allows through only the ones
not to io.stderr. Note that all file objects share the same metatable
and hence the same methods, and this can't be changed because it's the
identity of the metatable that is used to identify that it's a valid
file object in the first place.

local file_methods = getmetatable(io.stderr).__index  -- any file will do
local old_write = file_methods.write
file_methods.write =
    function(f,...)
        if f ~= io.stderr then
            return old_write(f,...)
        end
        return f
    end
-- note that errors here will leave the patched function in place,
-- you might need to use pcall to handle that
io.stderr:write("nope!")
io.stdout:write("yup!")
-- restore
file_methods.write = old_write
io.stderr:write("yup!")

-- 
Andrew.