4

How would I do something like this pseudo-code:

\if{#1==5 or \x>7}{Command 1}
\else{Command 2}

where #1 is some argument in a \newcommand and \x could come from a \foreach \x in {0,1,2}, for example. I'm trying to use etoolbox and after reading some pages of the manual I thought this could be a job for \ifboolexpr, but in every way I try to write it I receive an error of invalid boolean expression. I believe I'm basically asking what's the equivalent of this answer with the etoolbox package: Boolean operators: can I use AND, OR in `\ifthenelse`? How?

1 Answer 1

5

Welcome to TeX.SX! You may not need etoolbox for that:

\documentclass{article}

\usepackage{tikz}

\newcommand{\hello}[2]{%
  \ifnum #1 = 5
    Hello!
  \else
    \ifnum #2 > 7
      Hello!
    \else
      Bye!
    \fi
  \fi
}

\begin{document}

\foreach \x in {6,7,8} {

  A: \hello{4}{\x}
  
  B: \hello{5}{\x}
  
}

\end{document}

enter image description here

If you still want to use the macros provided by etoolbox, the following should work:

\newcommand{\hello}[2]{%
  \ifnumcomp{#1}{=}{5}{Hello!}{%
    \ifnumcomp{#2}{>}{7}{Hello!}{Bye!}}%
}

or

\newcommand{\hello}[2]{%
  \ifboolexpr{
    test {\ifnumcomp{#1}{=}{5}}
    or
    test {\ifnumcomp{#2}{>}{7}}
  }{Hello!}{Bye!}%
}
3
  • 2
    Hi, thanks for the answer! So the 3rd option is what I was looking for. But I imagined there could exist something more compact, because I'd have a lot of 'or', like \foreach \x in {0,...10} \if \x in {0,3,4,6,7,9} do_something (if the pythonic way worked). But I think I'll have to stick with one of these options, right? Commented Mar 22, 2021 at 19:36
  • I agree with Allan that the provided solution is overly verbose. Surely there is a better way?
    – Paul Wintz
    Commented Dec 7, 2023 at 7:34
  • @PaulWintz Well, you can always create your own custom macro that takes some arguments to simplify the code. I can't really remember what the use case was in this special case. There are indeed very diverse ways to compare numbers. I only provided some of the most common ways. What suits your needs best, depends on the concrete use case. Commented Dec 7, 2023 at 7:54

You must log in to answer this question.

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