1

I'd love to have a command with a boolean flag. That flag is supposed to be used in a conditional statement.

I'd love to have something like this:

\command             -> false
\command[flag=false] -> false

\command[flag]       -> true
\command[flag=true]  -> true

In the definition I'd have a switch like this:

\iftrue{#flag} true \else false \fi
  • Have a look at the key value packages we recommended yesterday, e.g. pgfkeys. See tex.stackexchange.com/questions/34312/… – TeXnician Aug 1 '18 at 14:11
  • that for example is exactly how clip works in \includegraphics (defined using the keyval package) – David Carlisle Aug 1 '18 at 14:11
  • Well, I see how I could create a value, but not how I could handle the \command[flag] case... – BrainStone Aug 1 '18 at 14:19
  • What's wrong with \newif\ifflag, \flagtrue, \flagfalse, \ifflag..\else..\fi? – Ulrich Diez Aug 2 '18 at 16:51
  • @UlrichDiez nothing other that I know nothing about conditionals in LaTeX – BrainStone Aug 2 '18 at 19:55
4

Use an advanced key-value interface, here is expl3:

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\command}{O{}}
 {
  \keys_set:nn { brainstone/command }
   {
    flag=false, % initialize to false
    #1
   }
  %
  \bool_if:NTF \l_brainstone_command_flag_bool
   {
    The ~ flag ~ is ~ set ~ to ~ true
   }
   {
    The ~ flag ~ is ~ set ~ to ~ false
   }
 }

\keys_define:nn { brainstone/command }
 {
  flag .bool_set:N = \l_brainstone_command_flag_bool,
  flag .default:n  = true,
 }

\ExplSyntaxOff

\begin{document}

\command           \ $\to$ false

\command[flag=false] $\to$ false

\command[flag]       $\to$ true

\command[flag=true]  $\to$ true

\end{document}

enter image description here

The flag will remain set in the current scope.

| improve this answer | |
  • A bit more complicated than I thought, but works like a charm! Thanks so much!! – BrainStone Aug 1 '18 at 14:36

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.