Lua 中的 TeX 條件

Lua 中的 TeX 條件

為什麼我可以使用

\startluacode
context.mymacro("\noexpand\\iftrue")
\stopluacode

但不是

\startluacode
context.mymacro([[\noexpand\iftrue]])
\stopluacode

或不

\startluacode
context.mymacro([[\unexpanded{\iftrue}]])
\stopluacode

或不

\startluacode
context.mymacro("\luaescapestring{\normalunexpanded{\iftrue}}")
\stopluacode

我相信\iftrue這是一個可擴展的原語。

編輯

\def\mymacro#1{%
    \let\mycond#1%
    \show\mycond}

答案1

\startluacode<code>\stopluacode大致翻譯為:

\begingroup
  <catcode settings> (basically verbatim, but \ is catcode 0)
  <shorthands> (\\ is defined to be the two backslash characters, as
    well as \|, \-, \(, \), \{, \}, etc.)
\normalexpanded {\endgroup \noexpand \directlua {<code>}}

讓你感到困擾的是<code>被擴展了兩次:一次由\normalexpanded\expanded原),再一次由\directlua

第一個有效,因為一旦 的擴充\normalexpanded結束,您就剩下\directlua{context.mymacro("\\iftrue")},它可以滿足您的要求。請注意,由於\\被定義為擴展為,因此您不需要那裡,因此您可以將第一個範例簡化為:\12\12\noexpand

\startluacode
context.mymacro("\\iftrue")
\stopluacode

第二個:

\startluacode
context.mymacro([[\noexpand\iftrue]])
\stopluacode

不起作用,因為 隨\noexpand一起消失\normalexpanded,只剩下\directlua{context.mymacro([[\iftrue]])},然後過早地\directlua展開。\iftrue你需要兩輪\noexpand

\startluacode
context.mymacro([[\noexpand\noexpand\noexpand\iftrue]])
\stopluacode

第三個:

\startluacode
context.mymacro([[\unexpanded{\iftrue}]])
\stopluacode

不起作用有三個原因:首先,在 ConTeXt 中\unexpanded\protected原語,而不是\unexpanded.你需要\normalunexpanded這裡。其次,\startluacode大括號內是catcode 12,因此\normalunexpanded會拋出Missing { inserted錯誤。第三次與上面相同:您有兩輪擴展,因此您需要兩輪\normalunexpanded

\everyluacode\expandafter{\the\everyluacode
  \catcode`\{=1 \catcode`\}=2\relax} % catcode setting to have braces be braces
\startluacode
context.mymacro([[\normalunexpanded{\normalunexpanded{\iftrue}}]])
\stopluacode

第四個:

\startluacode
context.mymacro("\luaescapestring{\normalunexpanded{\iftrue}}")
\stopluacode

不起作用的原因與上面相同:大括號是catcode 12,所以\luaescapestring永遠看不到它{需要的並拋出Missing { inserted錯誤。您需要先設定正確的目錄代碼:

\everyluacode\expandafter{\the\everyluacode
  \catcode`\{=1 \catcode`\}=2\relax} % catcode setting to have braces be braces
\startluacode
context.mymacro("\luaescapestring{\normalunexpanded{\iftrue}}")
\stopluacode

相關內容