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
  • 1
    Have a look at the key value packages we recommended yesterday, e.g. pgfkeys. See https://tex.stackexchange.com/questions/34312/how-to-create-a-command-with-key-values – TeXnician Aug 01 '18 at 14:11
  • that for example is exactly how clip works in \includegraphics (defined using the keyval package) – David Carlisle Aug 01 '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 01 '18 at 14:19
  • What's wrong with \newif\ifflag, \flagtrue, \flagfalse, \ifflag..\else..\fi? – Ulrich Diez Aug 02 '18 at 16:51
  • @UlrichDiez nothing other that I know nothing about conditionals in LaTeX – BrainStone Aug 02 '18 at 19:55
  • @BrainStone \newif\ifflag creates a new \if...-conditional. Calling \flagtrue causes \ifflag..\else..\fi to henceforth go the \if..-branch. Calling \flagfalse causes \ifflag..\else..\fi to henceforth go the \else..-branch. – Ulrich Diez Aug 03 '18 at 19:06

2 Answers2

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.

egreg
  • 1,121,712
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

Skillmon
  • 60,462