edef 中的 Lua 迴圈會出錯,但 newcommand 中不會出錯!如何用lua循環充分展開巨集?

edef 中的 Lua 迴圈會出錯,但 newcommand 中不會出錯!如何用lua循環充分展開巨集?

我怎麼才能擁有\edef一個帶有 lua 循環的 'ed(擴展)宏tex.sprint?當其中tex.sprint有另一個類似的巨集時,我收到錯誤。\blindtext[<n>]如果我列印一些非宏字串(例如在 lua 循環中Hello world!使用) ,我不會收到錯誤。tex.sprint如果我不擴展(不使用\edef)巨集定義並使用巨集定義,也不會發生該錯誤\newcommand。為什麼會這樣呢?

\newcommand下面是先使用, 然後使用 的程式碼\edef。首先按原樣運行程式碼,在第二次運行中取消註解\edef版本以查看錯誤:

! Use of \\blindtext doesn't match its definition.
\kernel@ifnextchar ...rved@d =#1\def \reserved@a {
                                                  #2}\def \reserved@b {#3}\f...

l.26    \directlua{dofile("blindtextloop.lua")}
                                           %
? 
% lualatex edefloop.tex
\documentclass[notitlepage,letterpaper]{article}
\usepackage[english]{babel}
\usepackage{blindtext}

\begin{document}

% Note: This will write file blindtextloop.lua in you current directory
\begin{filecontents*}{blindtextloop.lua}
    for i=0,3 do
        tex.sprint(" \\blindtext[1] \\par")
    end
\end{filecontents*}

% Unexpanded blindtext
\newcommand{\myblindtext}{%
    \directlua{dofile("blindtextloop.lua")}%
}%

Expanding next:

\myblindtext

%% Uncomment following lines in second run to see the error:
% %Expanded blindtext
% \edef\myblindtextexpanded{%
%   \directlua{dofile("blindtextloop.lua")}%
% }%

% Already expanded:

% \myblindtextexpanded


\end{document}

螢幕截圖: 編譯輸出的螢幕截圖

答案1

您可以在 edef 中擴充 Lua 循環,\blindtext但在本例中不需要擴充巨集,如終端輸出所示,這會導致定義 \myblindtextexpanded

macro:-> \blindtext [1] \par \blindtext [1] \par \blindtext [1] \par \blindtext
 [1] \par 

因此循環已展開為重複調用\blindtext.

% lualatex edefloop.tex
\documentclass[notitlepage,letterpaper]{article}
\usepackage[english]{babel}
\usepackage{blindtext}

\begin{document}

% Note: This will write file blindtextloop.lua in you current directory
\begin{filecontents*}{blindtextloop.lua}
    for i=0,3 do
        tex.sprint(" \\noexpand\\blindtext[1] \\par")
    end
\end{filecontents*}

% Unexpanded blindtext
\newcommand{\myblindtext}{%
    \directlua{dofile("blindtextloop.lua")}%
}%

Expanding next:

\myblindtext

%% Uncomment following lines in second run to see the error:
 %Expanded blindtext
 \edef\myblindtextexpanded{%
   \directlua{dofile("blindtextloop.lua")}%
 }%

% Already expanded:

\typeout{\meaning\myblindtextexpanded}

\myblindtextexpanded


\end{document}

相關內容