![luacode 适用于 \newcommand,但不适用于 \NewDocumentCommand](https://linux22.com/image/472259/luacode%20%E9%80%82%E7%94%A8%E4%BA%8E%20%5Cnewcommand%EF%BC%8C%E4%BD%86%E4%B8%8D%E9%80%82%E7%94%A8%E4%BA%8E%20%5CNewDocumentCommand.png)
想象一下以下代码:
\documentclass{book}
\usepackage{luacode}
\usepackage{xparse}
\NewDocumentCommand{\HelloWorld}{}{Hello World}
\newcommand{\DefaultHelloWorld}{Hello World}
\begin{luacode}
luatexbase.add_to_callback("wrapup_run", function()
io.write("\HelloWorld")
-- io.write("\DefaultHelloWorld")
end, "Post-process pdf")
\end{luacode}
\begin{document}
Hello World!
\end{document}
为什么使用\newcommand
可以正常工作并扩展为io.write("Hello World")
,但一旦我切换到 ,\NewDocumentCommand
就会出现以下错误(日志文件的摘录):
Package: xparse 2023-10-10 L3 Experimental document command parser
)[\directlua]:2: invalid escape sequence near '"\H'.
\luacode@dbg@exec ...code@maybe@printdbg {#1} #1 }
l.14 \end{luacode}
The lua interpreter ran into a problem, so the
remainder of this lua chunk will be ignored.
答案1
谢谢乌尔丽克·菲舍尔
只需切换到\NewExpandableDocumentCommand
:
\documentclass{book}
\usepackage{luacode}
% \usepackage{xparse} % REMOVED -- see @David Carlisle's comment
\NewDocumentCommand{\OldHelloWorld}{}{Hello World} % OLD
\NewExpandableDocumentCommand{\HelloWorld}{}{Hello World} % NEW -- working
\newcommand{\DefaultHelloWorld}{Hello World}
\begin{luacode}
luatexbase.add_to_callback("wrapup_run", function()
io.write("\HelloWorld")
-- io.write("\DefaultHelloWorld")
end, "Post-process pdf")
\end{luacode}
\begin{document}
Hello World!
\end{document}