5

I want to redirect tex.print output to a file to collect and reuse the produced LaTeX material :

the mwe :

\documentclass{article}

\begin{document}

essai

\directlua{require("essai.lua")}

\directlua{ a = "Hello word \\dots" }

\directlua{ to_file ( a ) }

\end{document}

and the lua script called essai.lua :

function to_file ( x )
    local file_name = "Foo"

    out = io.open( file_name .. ".tex", 'w' )

    tex.print = out:write

    out:write ( "\\documentclass{article}" )
    out:write ( "\\begin{document}")
    tex.print ( x )
    out:write ( "\\end{document}" )
    io.close( out )
end

The error message is :

(/usr/local/texlive/2022/texmf-dist/tex/latex/base/ts1cmr.fd)...2/texmf-dist/te x/luatex/lualibs/lualibs-basic-merged.lua:391: error loading module essai.lua f rom file ./essai.lua: ./essai.lua:9: function arguments expected near 'out'

3
  • Can you explain a bit more? Does this code already work, or not? Do you get errors? Which part works and which part does not? Or is it an answer and you forgot to post the question?
    – Marijn
    Commented Aug 14, 2022 at 14:50
  • This example doesn't work and is the purpose of the question. As you see one of the out:write that write normally to a file is remplaced by a tex.print. I have some complex document mostly produced using lua output, and I want to preserve the latex output to reuse it. It is why I want to save it to a file.
    – Tarass
    Commented Aug 14, 2022 at 15:00
  • Well this one is completely about Lua programming instead of TeX programming, but alright.
    – user202729
    Commented Aug 14, 2022 at 17:02

1 Answer 1

7

You can overwrite the function definition (see https://stackoverflow.com/a/4510038/):

function to_file ( x )
    local file_name = "Foo"

    out = io.open( file_name .. ".tex", 'w' )

    tex.print = function(trp)
        out:write(trp)
        out:write("\n")
    end

    out:write ( "\\documentclass{article}\n" )
    out:write ( "\\begin{document}\n")
    tex.print ( x )
    out:write ( "\\end{document}\n" )
    io.close( out )
end

Resulting Foo.tex with your MWE:

\documentclass{article}
\begin{document}
Hello word \dots
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .