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}

相關內容