[Tex/LaTex] Using a command to renew the command

macros

I've got:

\newcommand{\test}[1]{\renewcommand{\test}{#1}}

in a class file to make setting the command cleaner in the document itself.

This all works if the document contains:

\test{some content}

and outputs 'some content' when \test is used in the document.

But when I try to set \test to a new value with

\test{some other content} 

later, it seems to just output the value of \test and then 'some other content'.

How do I stop LaTeX expanding the \test and actually calling the \renewcommand to update the value?

Best Answer

The first usage of \test will redefine \test to a command without argument, that just outputs the argument of the first call. So your suggestion will not work. You have to use something like:

\newcommand{\test}{}
\newcommand{\settest}[1]{\renewcommand{\test}{#1}}

Then you can use

\settest{some content}
\test, \test, \test% shows "some contents" three times
\settest{some other content}
\test, \test% shows "some other contents" two times

You could use an optional argument, e.g., using xparse to distinguish between storing an argument and output of an argument:

\documentclass{article}
\usepackage{xparse}

\newcommand*{\testvalue}{}
\NewDocumentCommand{\test}{o}{%
  \IfNoValueTF{#1}{\testvalue}{\def\testvalue{#1}}%
}

\begin{document}
  Define: \test[some content]

  Show: \test, \test

  Define: \test[some other contents]

  Show: \test, \test.
\end{document}

But this would be against the principle that an optional argument should only modify the default behaviour of a command and not change it into a complete other command. So I would not recommend to do this.

Related Question