LuaLaTex - 如何使用数字,稍后在文档中计算

LuaLaTex - 如何使用数字,稍后在文档中计算

我试图在文档开头打印一个数字,比如说x。问题是,这个数字是在文档后面的部分计算出来的,例如x = 2 + 3

我如何在文档开头使用此计算的结果?类似的命令\tableofcontents也可以通过多个编译步骤执行类似操作,所以我认为这应该是可能的,但我被困在这里。你有什么建议吗?

答案1

在此处输入图片描述

和经典 tex 一样,你可以使用 aux 文件

\documentclass{article}


\gdef\mynumber{0}% first time
\begin{document}

The number will be \mynumber.

\makeatletter
\immediate\write\@auxout{\gdef\string\mynumber{\directlua{
n=1+2+3
tex.print(n)}}}
\makeatother

\end{document}

答案2

欢迎使用 TeX.SX!这是 LaTeX3 实现。它独立于 TeX 引擎(LuaTeX、pdfTeX、XeTeX……)。此外,对于 LaTeX 引用,如果结果自上次编译运行以来发生变化,您将收到警告(这意味着您应该重新编译以获得正确的输出)。传递给的算术表达式\writeresult使用\int_eval:n中描述的函数界面3.pdf(参见标题为l3int 包)。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\str_new:N \g_lemonbonbon_result_str
\str_new:N \g_lemonbonbon_previous_result_str

\msg_new:nnn { lemonbonbon } { additional-compilation-run-may-be-needed }
  { The~computed~result~has~changed;~another~compilation~run~may~be~needed. }

\cs_new_protected:Npn \lemonbonbon_write_result_to_aux_file:n #1
  {
    \cs_set_eq:cN { lemonbonbon@set@result } \relax % will not expand

    \iow_now:cx { @auxout }
      { \use:c { lemonbonbon@set@result } { \int_eval:n {#1} } }
  }

\NewDocumentCommand \writeresult { m }
  {
    \lemonbonbon_write_result_to_aux_file:n {#1}
  }

\NewDocumentCommand \useresult { }
  {
    \str_use:N \g_lemonbonbon_result_str
  }

\AtBeginDocument
  {
    % Save the previous result (this is run after the .aux file has been read)
    \str_gset_eq:NN \g_lemonbonbon_previous_result_str \g_lemonbonbon_result_str
  }

% Command run when the .aux file is reread, after the \AtEndDocument hook.
\cs_new_protected:Npn \lemonbonbon_warn_if_result_changed:n #1
  {
    \str_if_eq:VnF \g_lemonbonbon_previous_result_str {#1}
      {
        \msg_warning:nn { lemonbonbon }
                        { additional-compilation-run-may-be-needed }
      }
  }

% Reading the .aux file at end of document triggers comparison with the
% previous result in order to warn the user if it has changed.
\AtEndDocument
  {
    \cs_gset_eq:cN { lemonbonbon@set@result }
                   \lemonbonbon_warn_if_result_changed:n
  }

\makeatletter
% Command used in the .aux file (uses LaTeX2e naming conventions)
\NewDocumentCommand \lemonbonbon@set@result { m }
  {
    \str_gset:Nn \g_lemonbonbon_result_str {#1}
  }
\makeatother

\ExplSyntaxOff

\begin{document}
  The result is \useresult.

  \writeresult{3+4*(5-3)}
\end{document}

两次编译运行后的输出:

截屏

相关内容