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
6
  • 1
    Have a look at the key value packages we recommended yesterday, e.g. pgfkeys. See tex.stackexchange.com/questions/34312/…
    – TeXnician
    Aug 1, 2018 at 14:11
  • that for example is exactly how clip works in \includegraphics (defined using the keyval package) Aug 1, 2018 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, 2018 at 14:19
  • What's wrong with \newif\ifflag, \flagtrue, \flagfalse, \ifflag..\else..\fi? Aug 2, 2018 at 16:51
  • @UlrichDiez nothing other that I know nothing about conditionals in LaTeX
    – BrainStone
    Aug 2, 2018 at 19:55

2 Answers 2

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.

1
  • A bit more complicated than I thought, but works like a charm! Thanks so much!!
    – BrainStone
    Aug 1, 2018 at 14:36
0

Another solution using expkv with the expkv-def front end.

This solution uses a group to keep the effects of the key=value argument local. If using a group isn't possible for other reasons you could as well set flag=false before evaluating #1 in the \ekvset-call.

\documentclass{article}

\usepackage{expkv-def}

\ekvdefinekeys{brainstone}
  {
    boolTF flag = \brainstoneFlag
  }

\NewDocumentCommand\brainstone{O{}}
  {%
    \begingroup % group keeping the changes local
      \ekvset{brainstone}{#1}%
      The flag is set to \brainstoneFlag{true}{false}.%
    \endgroup
  }

\begin{document}
\brainstone

\brainstone[flag=false]

\brainstone[flag]

\brainstone[flag=true]
\end{document}

enter image description here

You must log in to answer this question.

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