lua-users home
lua-l archive

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


Hi All,

I'm trying to capture and redirect stdout and stderr (using pure Lua) to deliver the output remotely and ran into some problems. Some relevant discussions I found are http://lua-users.org/lists/lua-l/2007-04/msg00452.html and http://lua-users.org/lists/lua-l/2006-03/msg00023.html, but nothing that directly describes how to do this in Lua.

Here is my script that shows changing io.stdout doesn't seem to have any effect on print() and io.write:

local iobase = { output = io.output, stdout = io.stdout }
local copy = {
  write = function(self, ...) iobase[self.mode]:write("write ", ...) end,
}
copy.__index = copy

io.stdout = setmetatable({mode = "stdout"}, copy)
io.output = function(o) iobase.output(o) return io.stdout end
io.stdout:write("test 1\n") -- works
io.output():write("test 2\n") -- works
io.write("test 3\n") -- doesn't work
print("test 4") -- doesn't work

This prints:

write test 1
write test 2
test 3
test 4

I can definitely overwrite "print" and "io.write" with my own functions (maybe that's the easiest way to do this), but I'm looking for a cleaner way if there is any. I also tried to call io.output(copy) to make io.write() work, but it returned an error "bad argument #1 to 'output' (FILE* expected, got table)".

What is the right way do provide my handlers to replace stdout and stderr write? Thanks.

Paul.