Write LaTeX3 variable to aux file and recover it
Let's assume you have two integer variables \g_maxmaier_foo_int
and \l_maxmaier_bar_int
and that, at end document, you want to save the setting
\int_gset:Nn \g_maxmaier_foo_int { \int_eval:n { \l_maxmaier_bar_int } }
in the aux file, so that the value of the foo
variable is set at the beginning of the next run.
You have to surround this in \ExplSyntaxOn
and \ExplSyntaxOff
, otherwise the commands would not be interpreted correctly. Note also that the setting to the foo
variable must be global, because the aux file is read inside a group.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\int_new:N \g_maxmaier_foo_int
\int_new:N \l_maxmaier_bar_int
\NewDocumentCommand{\setbar}{m}
{
\int_set:Nn \l_maxmaier_bar_int { #1 }
}
\NewDocumentCommand{\showfoo}{}
{
\int_to_arabic:n { \g_maxmaier_foo_int }
}
\AtEndDocument
{
\iow_now:cx { @auxout }
{
\token_to_str:N \ExplSyntaxOn
^^J
\int_gset:Nn \g_maxmaier_foo_int { \int_eval:n { \l_maxmaier_bar_int } }
^^J
\token_to_str:N \ExplSyntaxOff
}
}
\ExplSyntaxOff
\begin{document}
The value of \texttt{foo} is \showfoo
\setbar{42}
\end{document}
Contents of the aux file
\relax
\ExplSyntaxOn
\int_gset:Nn \g_maxmaier_foo_int {42}
\ExplSyntaxOff
Some comments.
Adding
\int_eval:n
(or its synonym\int_use:n
) is essential, otherwise LaTeX would write\int_gset:Nn \g_maxmaier_foo_int { \l_maxmaier_bar_int }
which would be completely useless, because it would assign the value of
\l_maxmaier_bar_int
current at execution time, that is, when the.aux
file is being read; we want instead to fix the value of the variable at writing time (in the previous LaTeX run).For the same reason above, it's important to use
\iow_now:cx
(a variant for\iow_now:Nx
) so its argument is fully expanded at writing time.The token
^^J
makes a new line when a list of tokens is written in the.aux
file. It's the analog of\n
in other programming languages.