luacode は \newcommand では動作しますが、\NewDocumentCommand では動作しません。

luacode は \newcommand では動作しますが、\NewDocumentCommand では動作しません。

次のコードを想像してください。

\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}

関連情報