3

I would like to pass a newcommand to \label. Could you please help me how to do this?

My (uncompilable) MWE is the following:

\documentclass{article}

\usepackage{longtable}
\DeclareRobustCommand{\ltlab}{lab}

\begin{document}

\begin{longtable}{l}
\caption{This is a cool table.}
\label{table:{\ltlab}}
\end{longtable}

Table~\ref{table:{\ltlab}} contains nothing.

\end{document}

Update: @Phelype Oleinik reminded me that there was a typo in this MWE. After correcting this typo and using \newcommand instead of \DeclareRobustCommand, I received what I wanted to have.

4
  • I do not insist on using \DeclareRobustCommand, just to define a \label separately from what it points to (in the present case, to a \longtable).
    – TobiR
    Commented Jun 1, 2021 at 13:45
  • 1
    Don't declare the command with \DeclareRobustCommand, use \newcommand instead. Also, you have a typo in \label{table:{\ltab}}: it should be \label{table:{\ltlab}} (also the braces are unnecessary: you could write \label{table:\ltlab}). Commented Jun 1, 2021 at 13:45
  • 1
    @PhelypeOleinik I'd say that braces should be avoided. They're not “wrong”, but they produce a funny label.
    – egreg
    Commented Jun 1, 2021 at 13:49
  • Thanks, I works well.
    – TobiR
    Commented Jun 1, 2021 at 13:52

1 Answer 1

4

You use \DeclareRobustCommand when the command should survive full expansion that happens in \write operations. But the argument to \label and \ref needs quite the opposite: it should expand to a string of characters that's legal in the context of \csname...\endcsname.

Thus you should definitely use \newcommand, which does no such protection.

By the way, \label{table:{\ltlab}} is legal, but produces a funny label with braces having category code 12.

There's no need of adding those braces: \label{table:\ltlab} is cleaner, in my opinion.

You must log in to answer this question.

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