4

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?

  • 2
    You are using \test in two separate ways. The first time it defines it for future use. Thereafter, it uses the future-use definition for output. It would make more sense to have two commands: \newcommand{\settest}[1]{\renewcommand{\test}{#1}} to define (and redefine) it and \test to use it. In this case, you would need an initial \def\test{} definition, so that the \renewcommand would not choke. – Steven B. Segletes Apr 26 '17 at 14:26
3

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.

  • The first use of \test{some content} will correctly set and keep the value for multiple further uses of \test, i.e. \newcommand{\test}[1]{\renewcommand{\test}{#1}} \test{test}\test\test\test will output testtesttest. It just doesn't redefine the value of \test when \test{new value} is used. – Otis Apr 26 '17 at 14:33
  • @Otis This is exactly what I said. – Schweinebacke Apr 26 '17 at 14:36
  • "The first usage of \test will redefine \test to a command without argument" doesn't this imply that a second use of just \test will no longer store the value? Sorry if I'm misunderstanding. – Otis Apr 26 '17 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.