In the document end hook I'm trying to write \luaexec{x = 1}
to the aux file, where the 1
is computed in Lua itself (and more complex in the real document, of course). MWE:
\documentclass{article}
\usepackage{luacode}
\luaexec{x = 0}
\makeatletter
\AtEndDocument{%
\immediate\write\@auxout{%
\noexpand\luaexec{x = \luaexec{tex.sprint(1)}}}
}
\makeatother
\begin{document}
x = \luaexec{tex.sprint(x)}
\end{document}
Here are just some of the many errors I get from lualatex
:
[...]
Runaway argument?
{x = \begingroup \escapechar 92 \newlinechar 10 \edef \protect \let \relax \ETC.
! Paragraph ended before \luaexec was complete.
<to be read again>
\par
l.5
! LaTeX Error: Missing \begin{document}.
[...]
l.6 S
ee the LaTeX manual or LaTeX Companion for explanation.
! Missing control sequence inserted.
<inserted text>
\inaccessible
l.7 ...ken \let \edef \def document{document}\edef {
on input line 18}\protect...
! Improper \spacefactor.
\@o-\spacefactor
\@m
[...]
I assume this is because of the amusing stuff being written into my aux file, such as:
\relax
\luaexec {x = \begingroup \escapechar 92 \newlinechar 10 \edef \protect \let \relax \let \relax \let \reserved@d =*\def \def document{document}\edef { on input line 18}\protect \begingroup \immediate \write \@unused \def \MessageBreak
\let \protect \edef Your command was ignored.\MessageBreak Type I <command> <return> to replace it with another command,\MessageBreak or <return> to continue without it. \errhelp \let \def \MessageBreak
\def \errmessage LaTeX Error: Can be used only in preamble.
See the LaTeX manual or LaTeX Companion for explanation.
I tried this as well, but it fails in its own way:
\AtEndDocument{%
\edef\myCode{\noexpand\luaexec{x = \luaexec{tex.sprint(1)}}}
\immediate\write\@auxout{\myCode}
}
What am I doing wrong? Is it just hopeless to think that I can use \luaexec
here? Thanks!
.aux
file? Note that\write
doesn't do command execution, but just expansion.\luaexec{x = 1}
into the.aux
file, where the1
is computed in some Lua code.\luaexec
is not expandable: if you want to use Lua in such a context you'll need the\directlua
primitive.\luaexec
is "not purely expandable." I assume that's what @JosephWright is referring to as well. I don't understand "expandable-ness" and when/where it matters, but I can certainly understand "you need something expandable there and\luaexec
is not." I'd be happy to select this as the answer if you'd post it. Thank you!\luadirect
works.