lua-users home
lua-l archive

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




On Sat, Jun 20, 2020 at 7:14 AM Robert McLay <mclay@tacc.utexas.edu> wrote:
I would like to make calls to io.stderr:write() be silent sometimes but I am unable to redefine that function temporarily.   Below is a tiny example of what I tried.  This doesn't work.  What does?

Here's another approach, you make 'io.stderr' point to a proxy object that forwards all method calls to the original stderr except when you override it in the proxy. The advantage is that you don't touch any other file's metatable or methods.

The __index metamethod automatically creates a forwarding function for any method of stderr that's actually being used, unless you override it.

local original_stderr = io.stderr

local proxy = setmetatable({}, {
    __index = function(proxy, method)
        local m = original_stderr[method]
        local function forward(proxy, ...)
            return m(original_stderr, ...)
        end
        proxy[method] = forward
        return forward
    end
})

io.stderr = proxy


io.stderr:write("Hello, world\n")

proxy.write = function() end

io.stderr:write("You can't read this\n")

proxy.write = nil

io.stderr:write("Goodbye\n")


--