如何在 luatex 中访问 LaTeX 计数器?

如何在 luatex 中访问 LaTeX 计数器?

这个问题,我知道我可以使用 Lua 访问原始 TeX 计数tex.count[key],但是如何在 Lua 中访问 LaTeX 计数器?

梅威瑟:

\documentclass{article}

% This is TeX
\newcount\mycount
\mycount 4\relax
% end of TeX

\newcounter{mycountlatex}
\setcounter{mycountlatex}{5}

\begin{document}
\directlua{tex.print(tex.count['mycount'])}  

% How to do something like this?
% \directlua{tex.print(tex.count['mycountlatex'])}  

\end{document}

答案1

LaTeX 计数器可以作为 TeX 计数来访问,但 LaTeX 在名称前面添加了一个,c@因此在 TeX 中mycountlatex变为(c@mycountlatex来源)。

这意味着上面的 MWE 将变成:

\documentclass{article}

% This is TeX
\newcount\mycount
\mycount 4\relax
% end of TeX

\newcounter{mycountlatex}
\setcounter{mycountlatex}{5}

\begin{document}
\directlua{tex.print(tex.count['mycount'])}  

% How to do something like this?
\directlua{tex.print(tex.count['c@mycountlatex'])}  

\end{document}

答案2

向用户隐藏这些内部细节并定义一个latex.counter“做正确的事情(tm)”是一个好主意。在 Lua 中使用元表可以相对容易地做到这一点:

latex = latex or {}
latex.counter = latex.counter or {}

local counter = latex.counter
local count = tex.count

setmetatable(counter, {__index = function(t, key) 
    return count['c@' .. key]
  end} )

现在latex.counter[key]将返回 LaTeX 计数器的值key。这是一个完整的示例:

\documentclass{article}
\usepackage{luacode}

\begin{luacode*}
latex = latex or {}
latex.counter = latex.counter or {}

local counter = latex.counter
local count = tex.count

setmetatable(counter, {__index = function(t, key) 
    return count['c@' .. key]
  end} )
\end{luacode*}

% This is TeX
\newcount\mycount
\mycount 4\relax
% end of TeX

\newcounter{mycountlatex}
\setcounter{mycountlatex}{5}

\begin{document}
\directlua{tex.print(tex.count['mycount'])}  

% How to do something like this?
\directlua{tex.print(latex.counter['mycountlatex'])}  

\end{document}

相关内容