LuaLaTeX 编写 LaTeX 命令

LuaLaTeX 编写 LaTeX 命令

我正在尝试让 LuaLatex 自动化一些 LaTex。

例如如果我写:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage{tcolorbox,graphicx,tikz}

\usepackage[paperwidth=120pt, paperheight=120pt, margin=10pt]{geometry}
\begin{document}
    \begin{tcolorbox}[boxsep=0pt, left=0pt, right=0pt, top=0pt, bottom=0pt, sharpish corners, opacityframe=0, opacityback=0, boxrule=0pt]
        \begin{tikzpicture}[x=1pt, y=1pt]
            \draw[line width=0mm, white] (0,0) -- (100,0) -- (100,100) -- (0, 100);
            \draw[xshift=50, yshift=50] node[draw, anchor=north west]{AAA};
        \end{tikzpicture}
    \end{tcolorbox}
\end{document}

我的构建成功了。

现在我想让 Lua 写下这一行:

            \draw[xshift=50, yshift=50] node[draw, anchor=north west]{AAA};

如果我写:


\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage{tcolorbox,graphicx,tikz}
\directlua{dofile("placeTextNode.lua")}
\newcommand*{\textNode}{%
    \directlua{tex.write(textNode())}%
}

\usepackage[paperwidth=120pt, paperheight=120pt, margin=10pt]{geometry}
\begin{document}
    \begin{tcolorbox}[boxsep=0pt, left=0pt, right=0pt, top=0pt, bottom=0pt, sharpish corners, opacityframe=0, opacityback=0, boxrule=0pt]
        \begin{tikzpicture}[x=1pt, y=1pt]
            \draw[line width=0mm, white] (0,0) -- (100,0) -- (100,100) -- (0, 100);
            \textNode
        \end{tikzpicture}
    \end{tcolorbox}
\end{document}

function textNode()
    return "\draw[xshift=50, yshift=50] node[draw, anchor=north west]{AAA};"
end

我收到一条错误消息:

‘”\d’ 附近的转义序列无效

如果我写:

function textNode()
    return "\\draw[xshift=50, yshift=50] node[draw, anchor=north west]{AAA};"
end

在 \draw 前面添加了 \ 后,我不再有错误,但是节点没有出现。

您知道我应该用 Lua 写什么吗?

谢谢。

答案1

正如文档中所写,tex.write旨在“用作转储信息的快速方法”。它有意调整 catcodes 以确保其结果不是被解释为特殊的 TeX 命令。要传递 TeX 代码,您需要以下函数之一tex.print/sprint/tprint。由于您想使用标准 catcode 打印整行,因此tex.print最合适的是:

\documentclass{article}

% \usepackage[utf8]{inputenc}
\usepackage{tcolorbox,graphicx,tikz}
\directlua{dofile("placeTextNode.lua")}
\newcommand*{\textNode}{%
    \directlua{tex.print(textNode())}%
}

\usepackage[paperwidth=120pt, paperheight=120pt, margin=10pt]{geometry}
\begin{document}
    \begin{tcolorbox}[boxsep=0pt, left=0pt, right=0pt, top=0pt, bottom=0pt, sharpish corners, opacityframe=0, opacityback=0, boxrule=0pt]
        \begin{tikzpicture}[x=1pt, y=1pt]
            \draw[line width=0mm, white] (0,0) -- (100,0) -- (100,100) -- (0, 100);
            \textNode
        \end{tikzpicture}
    \end{tcolorbox}
\end{document}

在此处输入图片描述

相关内容