12

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}
2
  • please fix your example, which generates ! Undefined control sequence. <argument> \mycountlatex l.8 \newcounter{\mycountlatex} (latex counters have no \ in the name. Commented Sep 13, 2016 at 8:56
  • Ah yes, my mistake! Commented Sep 13, 2016 at 8:57

2 Answers 2

11

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}
2
  • 1
    No. This generates the same error as the noted in the comment under the question. Commented Sep 13, 2016 at 8:57
  • Now tested and fixed. Commented Sep 13, 2016 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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .