redirecting the output of print()

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

redirecting the output of print()

Niccolo Medici
I want to redirect the output of print() to a file of my choosing.

(I know I can do "$ lua program.lua > output.txt", but I need to
create several output files. My program is already written and I don't
want to modify it too much.)

I tried this:

    io.output('out.txt')
    print('hello world')

But this doesn't work (on both Lua 5.2 and 5.3): it creates an empty
file named "out.txt" but keeps sending the output to the terminal (I'm
using Linux, BTW).

The documentation for print() says it prints "to stdout", and the
documentation for io.output() says that it "opens the named file and
sets its handle as the default output file". So I don't undertand why
my code doesn't work.

Reply | Threaded
Open this post in threaded view
|

Re: redirecting the output of print()

Luiz Henrique de Figueiredo
print is not part of the io library and so does not know about io.output.

You can redefine print to use the io library:

function print(...)
        local a=table.pack(...)
        local t=""
        for i=1,a.n do
                io.write(t,tostring(a[i]))
                t="\t"
        end
        io.write("\n")
end

Reply | Threaded
Open this post in threaded view
|

Re: redirecting the output of print()

Matthew Wild
In reply to this post by Niccolo Medici
On 21 June 2018 at 17:22, Niccolo Medici <[hidden email]> wrote:
> I want to redirect the output of print() to a file of my choosing.
>
> (I know I can do "$ lua program.lua > output.txt", but I need to
> create several output files. My program is already written and I don't
> want to modify it too much.)

You could re-implement print() at the start of your program, something
like this:

function print(...)
        local n_param = select("#", ...);
        for i = 1, n_param do
                io.write(tostring((select(i, ...))), i<n_param and
"\t" or "\n");
        end
end

Regards,
Matthew

Reply | Threaded
Open this post in threaded view
|

Re: redirecting the output of print()

云风 Cloud Wu
In reply to this post by Niccolo Medici

Niccolo Medici <[hidden email]>于2018年6月22日周五 上午12:23写道:
I want to redirect the output of print() to a file of my choosing.

(I know I can do "$ lua program.lua > output.txt", but I need to
create several output files. My program is already written and I don't
want to modify it too much.)

I tried this:

    io.output('out.txt')
    print('hello world')

But this doesn't work (on both Lua 5.2 and 5.3): it creates an empty
file named "out.txt" but keeps sending the output to the terminal (I'm
using Linux, BTW).

You can write a small C library to call dup2() to redirect stdout to a file, if you are using Linux.