How to access LaTeX counters in luatex?

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}

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}

Tags:

Luatex