I'm trying to label items on a table. In my use, multiple labels may exist, so the initial location of the creation of the label is irrelevant (not trying to hyperlink). I want to use one command that will assign a label. So I thought the easy solution would be to check if the reference exists, if not, increment a counter and assign a new label, otherwise reference it.
I do notice that I get different results alternating compiles. I also notice that when testing the ifundefined
part in isolation (i.e. print true or false), it takes two compiles. I believe this is because of the way TeX interacts with its .aux file ?
\documentclass{article}
\newcounter{myrefcnt}% my referene counter
\makeatletter
\newcommand\myref[1]{% my command
\@ifundefined{r@#1}{%if reference doesnt exist
\refstepcounter{myrefcnt}\themyrefcnt\label{#1}% create a label for reference
}{%
\ref{#1}% else reference it
}%
}
\makeatother
\begin{document}
\textbf{My Attempt:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & \myref{fourlegs}, \myref{lookslikerat} \\
Bat & \myref{lookslikerat} \\
Cheetah & \myref{fourlegs} \\\hline
\end{tabular}
\myref{fourlegs} indicates speciment has four legs.
\myref{lookslikerat} indicates speciment looks like a rat.
\textit{When I run the file, the labels are sometimes 1,2,3,4, but other times 5,6,6,5}
\textbf{I want to produce the following:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & 1, 2 \\
Bat & 2 \\
Cheetah & 1 \\\hline
\end{tabular}
1 indicates speciment has four legs.
2 indicates speciment looks like a rat.
\end{document}
\label
writes to the aux file which is read at begin document so all the r@.. macros are defined on the second run. you could make a global\my@'#1
macro that you don't record the the aux, but then test that in your macro in the same way. (You probably wouldn't need\label
at all in that case. – David Carlisle Nov 20 '20 at 14:06