我需要从我的 LuaLaTeX 文档中传递一些文本字符串作为文件名。这是一种 MWE:
\documentclass{article}
\usepackage{luamplib}
\def\testfilename{test1}
\def\writesomewords#1#2{
\begin{mplibcode}
beginfig(0);
string somewords;
somewords = "somewords";
draw textext("#1");
draw textext("#2") shifted (0, -1cm);
write somewords to "#1.txt";
write EOF to "#1.txt";
write somewords to "#2.txt";
write EOF to "#2.txt";
endfig;
\end{mplibcode}
}
\begin{document}
\writesomewords{\testfilename}{test2}
\end{document}
大多数情况下,参数都能正确传递,并且两个draw textext("...");
子句都会产生预期的结果:
但是,当涉及到文件名时,第二个文件test2.txt
按预期命名,但由于某种原因,第一个文件最终被调用\testfilename
(作为原始宏,它包含预期的名称)。显然,它在这个特定情况下没有扩展。
这可能是一个错误(这很有可能,因为类似的代码在 ConTeXt 中运行良好),在这种情况下我会报告它,但它可能只是一种预期的行为,在这种情况下:我如何扩展文件名以便它最终成为文件名?
答案1
mplibcode
阻止扩展,但您可以\expanded
先使用扩展参数
\documentclass{article}
\usepackage{luamplib}
\def\testfilename{test1}
\def\writesomewords#1#2{
\expanded{\noexpand\begin{mplibcode}
beginfig(0);
string somewords;
somewords = "somewords";
draw textext("#1");
draw textext("#2") shifted (0, -1cm);
write somewords to "#1.txt";
write EOF to "#1.txt";
write somewords to "#2.txt";
write EOF to "#2.txt";
endfig;
\noexpand\end{mplibcode}}
}
\begin{document}
\writesomewords{\testfilename}{test2}
\end{document}
生产test1.txt
somewords
和
答案2
我将使用一个辅助宏来向其传递扩展的参数:
\documentclass{article}
\usepackage{luamplib}
\newcommand{\testfilename}{test1}
\newcommand{\writesomewords}[2]{%
\ExpandArgs{ee}\writesomewordsaux{#1}{#2}%
}
\newcommand{\writesomewordsaux}[2]{%
\begin{mplibcode}
beginfig(0);
string somewords;
somewords = "somewords";
draw textext("#1");
draw textext("#2") shifted (0, -1cm);
write somewords to "#1.txt";
write EOF to "#1.txt";
write somewords to "#2.txt";
write EOF to "#2.txt";
endfig;
\end{mplibcode}%
}
\begin{document}
\writesomewords{\testfilename}{test2}
\end{document}
如果你运行的是旧版 LaTeX 发行版,请替换为
\newcommand{\writesomewords}[2]{%
\expanded{\noexpand\writesomewordsaux{#1}{#2}}%
}