将 tex.print 输出重定向到文件

将 tex.print 输出重定向到文件

我想将tex.print输出重定向到文件以收集和重新使用生成的LaTeX材料:

mwe

\documentclass{article}

\begin{document}

essai

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

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

\directlua{ to_file ( a ) }

\end{document}

并且 lua 脚本调用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

错误信息是:

(/usr/local/texlive/2022/texmf-dist/tex/latex/base/ts1cmr.fd)...2/texmf-dist/te x/luatex/lualibs/lualibs-basic-merged.lua:391:从文件 ./essai.lua 加载模块 essai.lua 时出错:./essai.lua:9:‘out’附近应有函数参数

答案1

您可以覆盖函数定义(参见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

您的 MWE结果是Foo.tex

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

相关内容