1

I need to test if one of multiple is defined. I know this command:

\ifIsDefined{\MYVAR}{
    % Do sometyhing
}

But, I need to test for two conditions like

if A or B is defined, then do this

How can you do this?

.

  • 2
    If nothing else, \ifA\doit\else\ifB\doit\else\fail\fi\fi. There are several packages to help with conditionals. Are you open to using them? What are the conditions that you want to test, and the actions that you want to take? – Teepeemm May 26 at 12:22
  • I am open to small libraries. I need to be able to execute the same code in two cases but not the third case. – 7heViking May 27 at 5:01
2

Use the package ifthen which is small to test if something is defined.

\ifthenelse{\(\NOT \isundefined{\MYVAR} \OR \NOT \isundefined{\MYSECONDVAR}\)}
{
    %True case
}
{
    % False case
}

See more examples here: https://riptutorial.com/latex/example/28656/if-statements

| improve this answer | |
1

Essentially no additional package, because expl3 is now loaded in the LaTeX kernel. You could even dispense with xparse by doing

\ExplSyntaxOn
\newcommand{\xifthenelse}[3]
 {
  \bool_if:nTF { #1 } { #2 } { #3 }
 }

in the first few lines, but I'd avoid it and prefer xparse for consistency. The code is drawn from another answer of mine.

What's the difference with \ifthenelse from ifthen? That this new implementation has fully expandable tests. In the first argument of \xifthen you can use any of the defined tests linked together with ! (for “not”), && (for “and”) or || (for “or”) and normal parentheses.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewExpandableDocumentCommand{\xifthenelse}{mmm}
 {
  \bool_if:nTF { #1 } { #2 } { #3 }
 }

\cs_new_eq:NN \numtest     \int_compare_p:n
\cs_new_eq:NN \oddtest     \int_if_odd_p:n
\cs_new_eq:NN \fptest      \fp_compare_p:n
\cs_new_eq:NN \dimtest     \dim_compare_p:n
\cs_new_eq:NN \deftest     \cs_if_exist_p:N
\cs_new_eq:NN \namedeftest \cs_if_exist_p:c
\cs_new_eq:NN \eqdeftest   \token_if_eq_meaning_p:NN
\cs_new_eq:NN \streqtest   \str_if_eq_p:ee
\cs_new_eq:NN \emptytest   \tl_if_blank_p:n
\prg_new_conditional:Nnn \xxifthen_legacy_conditional:n { p,T,F,TF }
 {
  \use:c { if#1 } \prg_return_true: \else: \prg_return_false: \fi:
 }
\cs_new_eq:NN \boolean \xxifthen_legacy_conditional_p:n
\ExplSyntaxOff

\begin{document}

\xifthenelse{ \deftest\MYVAR || \deftest\MYSECONDVAR }{%
  One of them is defined%
}{
  Neither is defined%
}

\newcommand\MYVAR{x}

\xifthenelse{ \deftest\MYVAR || \deftest\MYSECONDVAR }{%
  One of them is defined%
}{
  Neither is defined%
}

\end{document}

enter image description here

| improve this answer | |

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.