Building Latex/Tex arguments in lua

2019-08-04 12:40发布

问题:

I use lua to make some complex job to prepare arguments for macros in Tex/LaTex.

Part I Here is a stupid minimal example :

\newcommand{\test}{\luaexec{tex.print("11,12")}}% aim to create 11,12
\def\compare#1,#2.{\ifthenelse{#1<#2}{less}{more}}
\string\compare11,12. : \compare11,12.\\ %answer is less
\string\test : \test\\ % answer is 11,12
\string\compare : \compare\test. % generate an error

The last line creates an error. Obviously, Tex did not detect the "," included in \test.

How can I do so that \test is understood as 11 followed by , followed by 12 and not the string 11,12 and finally used as a correctly formed argument for \compare ?

回答1:

There are several misunderstandings of how TeX works.

Your \compare macro wants to find something followed by a comma, then something followed by a period. However when you call

\compare\test

no comma is found, so TeX keeps looking for it until finding either the end of file or a \par (or a blank line as well). Note that TeX never expands macros when looking for the arguments to a macro.

You might do

\expandafter\compare\test.

provided that \test immediately expands to tokens in the required format, which however don't, because the expansion of \test is

\luaexec{tex.print("11,12")}

and the comma is hidden by the braces, so it doesn't count. But it wouldn't help nonetheless.

The problem is the same: when you do

\newcommand{\test}{\luaexec{tex.print("11,12")}}

the argument is not expanded. You might use “expanded definition” with \edef, but the problem is that \luaexec is not fully expandable.

If you do

\edef\test{\directlua{tex.sprint("11,12")}}

then

\expandafter\compare\test.

would work.



标签: lua latex tex