Luatex は、Tex から Lua に可変数の引数を渡します (カンマで区切られ、エスケープされます)

Luatex は、Tex から Lua に可変数の引数を渡します (カンマで区切られ、エスケープされます)

複数の引数をTexコマンドからLua関数に渡し、同時にエスケープするにはどうすればよいでしょうか。

または、どのように変更すればよいですか

(輸入品)

\usepackage{luacode}
\newcommand{\example}[1]{
    \directlua{
        function debug(...)
            local arr = {...}
            for i, v in pairs(arr) do
                print(v)
            end
        end
        debug(#1)
    }
}

そのような

\example{\notDefined, aNilValue, 5}

標準出力を生成する

\notDefined
aNilValue
5

投げる代わりに

  • 未定義の制御シーケンス(ラテックスエラー)
  • または変数がaNilValue定義されていないため何も出力されない

\luastring{\unexpanded{...}}with を使ってみました\docsvlistが、引数が暴走し続けます

編集 明確に言えば、渡される引数はすべて文字列である必要があるため、local arr = {...}例では等しい必要があります。{"\\notDefined", "aNilValue", "5"}

答え1

空白をもっと考慮することもできますが、これにより、リスト全体の lua 文字列が作成され、その後コンマで分割されるため、すべての項目が文字列として解釈されます。

\newcommand{\example}[1]{%
    \directlua{
        function debug(s)
            for v in string.gmatch(s,'[^,]*') do
                print(v)
            end
        end
        debug("\luaescapestring{\detokenize{#1}}",",")
    }%
}

\typeout{}

\example{\notDefined, aNilValue, 5}

\stop

端末出力を生成する


\notDefined 
 aNilValue
 5

答え2

このソリューションでは、LaTeX3 のカンマ区切りリストを使用します。 の引数は\exampleログ ファイルに書き込まれます。

\documentclass{article}
\usepackage{expl3}

\directlua{
  function debug(...)
      local arr = {...}
      for i, v in pairs(arr) do
          texio.write_nl(v)
      end
  end
}

\ExplSyntaxOn
\newcommand{\example}[1]{
  % construct comma separated list
  \clist_set:Nn \l_tmpa_clist {#1}
  % construct lua string for each component
  % and store them in a sequence
  \seq_clear:N \l_tmpa_seq
  \clist_map_inline:Nn \l_tmpa_clist {
    \str_set:Nn \l_tmpa_str {##1}
    \seq_put_right:Nx \l_tmpa_seq {"\luaescapestring{\l_tmpa_str}"}
  }
  \directlua{debug(\seq_use:Nn \l_tmpa_seq {,})}
}
\ExplSyntaxOff

\begin{document}
\example{\notDefined, aNilValue, 5}
\end{document}

関連情報