11

In the same vein as this question, I know I can access raw TeX counts with Lua using tex.count[key], but how do I access a LaTeX counters in Lua?

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['mycountlatex'])}  

\end{document}
  • please fix your example, which generates ! Undefined control sequence. <argument> \mycountlatex l.8 \newcounter{\mycountlatex} (latex counters have no \ in the name. – David Carlisle Sep 13 '16 at 8:56
  • Ah yes, my mistake! – Nathanael Farley Sep 13 '16 at 8:57
9

LaTeX counters can be accessed as TeX counts, but LaTeX prepends the name with a c@ so mycountlatex becomes c@mycountlatex in TeX (source).

This means the MWE above would become:

\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}
  • 1
    No. This generates the same error as the noted in the comment under the question. – David Carlisle Sep 13 '16 at 8:57
  • Now tested and fixed. – Nathanael Farley Sep 13 '16 at 8:59
6

It is a good idea to hide such internal details from the user and define a latex.counter that "does the right thing(tm)". This is relatively easy to do in Lua using metatables:

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} )

Now latex.counter[key] will return the value of the LaTeX counter key. Here is a complete example:

\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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.