Tabularray: Macros & counters inside table

expansiontabularray

Working with the tabularray package, I'm trying to use a macro that operates a counter inside a table, like so:

\documentclass{article}

\usepackage{tabularray}

\begin{document}

\newcounter{dbg}

\newcommand{\ctr}{\refstepcounter{dbg}\arabic{dbg}}

\ctr
\ctr
\ctr

\begin{tabular}{ccc}
    \ctr & \ctr & \ctr \\
    \ctr & \ctr & \ctr \\
\end{tabular}

\begin{tblr}{ccc}
    \ctr & \ctr & \ctr \\
    \ctr & \ctr & \ctr \\
\end{tblr}

\end{document}

The \ctr macro works fine outside of tables and in a regular tabular, but inside tabularray, the results areā€¦ surprisingly large.

screenshot of LaTeX code shown above, showing a line with 1 2 3, a table with numbers 4 though 9, and a table with number 29, 32, 35, 38, 41, 44

It looks like tabularray is expanding the macro multiple times internally.

The \NewTableCommand mechanism isn't allowed to produce cell text, so it doesn't seem to help me. There's the (somewhat limited) expand option, but I haven't seen it have any effect on this, and neither did I find a way to sneak in a \protect or \noexpand to make it work.
Splitting the counting and printing into two commands, a \NewTableCommand-defined one that steps the counter and a regular one to print it almost works, but all the stepping is done before the table is set, so all cells show the final value of the counter.

Is there some way to get tabularray to expand my cells as intended?

Best Answer

The package evaluates the body multiple times for trial typesetting there is an issue in its github about that. Code was added to allow preserving counters based on the mechanism tabularx uses to preserve counters

https://github.com/lvjr/tabularray/discussions/83 and linked issues

As shown there, in recent releases you can use

\UseTblrLibrary{counter} 

which loads code that fixes this (by storing and restoring counter values).