7

I need some help understanding if statements.

How do I make the following pseudocode in LaTeX.

\newcommand{\@leader}{}
\newcommand{\leader}[1]{\renewcommand\@leader{#1}}

\newcommand{\donow}{
    \if \@leader == {}        %aka blank, null, empty
        this is the false     %do false
    \else   
        \@leader              %do leader
    \fi
}

Such that when a user adds the following to their document

\leader{
    \begin{itemize}
        \item this is an item
        \item this is also an item
    \end{itemize}
}

\donow

\leader{}

\donow

print the following

*This is an item

*this is also an item

this is the false

My only question about variables is, is the solution I have really the best way to do make variables?

0

2 Answers 2

8

You can test macro-to-macro using \ifx. That is, \ifx<csA><csB><true>\else<false>\fi will test whether the definition of <csA> matches that of <csB> and execute <true>, or <false> otherwise:

enter image description here

\documentclass{article}

\makeatletter
\newcommand{\@emptymacro}{}% Used to test against an empty macro
\newcommand{\@something}{}
\newcommand{\something}[1]{\renewcommand\@something{#1}}

\newcommand{\donow}{%
  \ifx\@something\@emptymacro %aka blank, null, empty
    this is the false     %do false
  \else
    \@something           %do something
  \fi
}
\makeatother

\begin{document}
\something{%
  \begin{itemize}
    \item this is an item
    \item this is also an item
  \end{itemize}
}

\donow

\something{}

\donow

\end{document}

etoolbox provides similar checking mechanism:

\usepackage{etoolbox}
\makeatletter
\newcommand{\@something}{}
\newcommand{\something}[1]{\renewcommand\@something{#1}}

\newcommand{\donow}{%
  \ifdefempty{\@something}{%aka blank, null, empty
    this is the false     %do false
  }{%
    \@something           %do something
  }%
}
\makeatother
1
  • Thank you Werner. I was traveling down the path of \newif and was stuck going in circles.
    – Bob
    Commented Apr 27, 2015 at 5:36
3

The standard TeX code for given task is:

\def\something#1{\def\internal{#1}%
   \ifx\internal\empty the parameter is empty.\else it is nonempty.\fi
}

The problem of this code (above) is that the macro \something isn't expandable because it includes \def assignment. If you need expandable macro with the same test then you need to choose the token never used as the first token in the parameter (say ? in our example) and you can write:

\def\something#1{\ifx?#1?the parameter is empty.\else it is nonempty.\fi}

If you don't know what token never occurs as first token of the parameter then you can use expandable \detokenize primitive from eTeX for example:

\if\penalty\detokenize{#1}\penalty the parameter empty.\else non-empty.\fi

You must log in to answer this question.

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