4

I want to pass a parameter to a command that I use in several places in my document. I want to set the parameter in the preamble so that I don't have to use edit the command further down in my document.

My MWE: I have to alternative sample-sizes to report in note to table. I want to pick the correct by setting a parameter in preamble.

\documentclass{article}
\usepackage{etoolbox}

\newcommand{\fixsmpl}[1]{%
    \ifstrequal{#1}{l}%
    {Sample runs from april to may}%
    {\ifstrequal{#1}{s}{Sample 2}{\PackageError{fixsmpl}{Undefined option to fixsmpl command}{}}}%
}

\def\X{s}

\begin{document}

% Works fine
\fixsmpl{s}

% Doesn't work 
\fixsmpl{\X}

\end{document}

I'm puzzled because I'm able to pass parameter in the example below:

%preamble
\newcommand{\inputtable}[2]{\input{../tables/table#1#2}}
\def\Z{2dp}

\begin{document}

\inputtable{1}{_\Z}
  • 1
    If you change your \ifstrequals to \ifdefstring, \fixsmpl{\X} will work, but \fixsmpl{s} won't. The problem here is expansion. \ifstrequal compares its two arguments without expansion, i.e. without unpacking the definition of macros. So \X is not expanded to s. If you use \ifdefstring, the first argument has to be a macro (like \X), so it breaks down if you feed it s. Something like gist.github.com/moewew/8ef53a51c97e52ab33a57c73eecbe5d5 would work (because we expand the macro with \edef). expl3/LaTeX3 has more elegant string comparison macros. – moewe Jul 3 at 8:29
  • 1
    Welcome back, Dagfinn, to TeX.SE! – Mico Jul 3 at 8:30
1

The macro \ifstrequal does no expansion to its arguments. One could define a new one that does, but it's probably better to avoid heavy nesting with the help of expl3.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewExpandableDocumentCommand{\fixsmpl}{m}
 {
  \str_case_e:nVF { #1 } \c_dagfinn_fixsmpl_tl
   {
    \PackageError{fixsmpl}{Undefined ~ option ~ to ~ fixsmpl ~ command}{}
   }
 }
\prg_generate_conditional_variant:Nnn \str_case_e:nn {nV} {T,F,TF,p}

\NewDocumentCommand{\fixsmplcases}{m}
 {
  \tl_const:Nn \c_dagfinn_fixsmpl_tl { #1 }
 }
\ExplSyntaxOff

\fixsmplcases{
  {s}{Sample 2}
  {l}{Sample runs from April to May}
  {t}{Sample runs from June to September}
}

\newcommand{\X}{s}
\newcommand{\Y}{t}

\begin{document}

% Fine
\fixsmpl{s}

% Fine
\fixsmpl{\X}

% Fine
\fixsmpl{\Y}

% Error
\fixsmpl{z}

\end{document}

The reason for the indirection (I mean the use of \fixsmplcases outside \ExplSyntaxOn...\ExplSyntaxOff is to avoid the need of denoting spaces with ~, which could be cumbersome.

You can define as many cases as you want.

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.