lua-users home
lua-l archive

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


I really appreciate the answers.  Thanks to you both, Andrew and Luis, for a very clear explanation.

Robert.

On Sat, Jun 20, 2020 at 10:07 AM Andrew Gierth <andrew@tao11.riddles.org.uk> wrote:
>>>>> "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.
>> This message is from an external sender. Learn more about why this <<
>> matters at https://links.utexas.edu/rtyclf.                        <<



--
Robert McLay, Ph.D.
Manager of Software Tools, HPC
mclay@tacc.utexas.edu