5

I'm trying to redirect stdout in Lua (5.1) to a file instead of to console.

There is a third-party API (which I cannot modify) containing a function that prints out a serialized set of data (I do not know which function does the printing, assume some sort of print())

This data is far too verbose to fit on the screen I have to work with (which cannot be scrolled) so I want to have the function's output be directed to a file instead of to console.

I do not have the ability to patch or manipulate Lua versions.

My thought was to change stdout to a file using the poorly documented io.output() file, but this does not seem to work at all.

 io.output("foo")   -- creates file "foo", should set stdout to "foo"?
 print("testing. 1, 2, 3") -- should print into "foo", goes to console instead

Does anyone know of any way to force a functions output into a file, or force all stdout into a file instead of console? TIA.

cwbit
  • 88
  • 1
  • 6

2 Answers2

3

You need to use io.write method instead of print. It works in a similar way, but doesn't separate parameters with a tab. io.write respects io.output, but print doesn't.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • 1
    the actual printing is done from inside the 3rd party API function, which I cannot change - so this won't help :/ (but is good to know otherwise). – cwbit Nov 19 '14 at 04:48
  • 4
    It's a different question ;). If the API function still use global `print` function (and not its C API equivalent), you can substitute with your own `print`: `print = function(...) io.write(table.concat({...}, "\t") end`. If it's using C API, I don't think there is a way to redirect or monkeypatch this. See this thread for details: http://lua-users.org/lists/lua-l/2012-11/msg00125.html – Paul Kulchenko Nov 19 '14 at 05:02
  • There is a fs API in computercraft. If I remember correctly then its used like: `foo = fs.open("foo", "w")` `foo.writeLine("testing. 1, 2, 3")` `foo.close()` – CHlM3RA Nov 19 '14 at 09:32
2
-- save, might need to restore later
real_stdout = io.stdout

file = io.open ('stdout.log', 'w')
io.stdout = file

.... -- call external API

-- restore
io.stdout = real_stdout
  • 2
    Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See [Explaining entirely code-based answers](meta.stackexchange.com/questions/114762/). – Calos Mar 10 '20 at 00:58