How can I have an \edef'ed (expanded) macro that has a lua loop with tex.sprint in it? I get an error when tex.sprint has another macro like \blindtext[<n>] in it. I do not get error if I print some non-macro strings like Hello world! using tex.sprint in the lua loop. The error also does not happen in case I do not expand (do not use \edef) the macro definition, and use \newcommand instead. Why is that so?
Below is the code that first uses \newcommand, and then \edef. First run the code as it is, in the second run uncomment the \edef version to see the error:
! 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}

\blindtextis not expandable (like everything that scans for optional arguments). – Henri Menke Sep 14 '20 at 03:37\futurelet, which is used to implement any type of optional argument scanning is one of them. – Henri Menke Sep 14 '20 at 05:21\edef\foo{\blindtext}generates the error you show, and doing that in a lua (or tex) loop doesn't stop that. – David Carlisle Sep 14 '20 at 06:35\blindtextunexpandable is the presence of optional arguments, can such problem be cleanly solved by taking care of optional arguments in lua? (while tex thinks there are no optional arguments?) Just curious... – codepoet Sep 14 '20 at 06:44\unexpanded, i.e.tex.sprint("\\unexpanded{\\blindtext[1]}\\par"), but it's really an XY-problem. – Henri Menke Sep 14 '20 at 07:07\unexpandedbut using\unexpandedin\edefis more or less the same as just using\def. – David Carlisle Sep 14 '20 at 07:13