1

Using pgfkeys, I have keys called a, b, and c. If the value of the key c is not set, then I want its value to depend on the other keys. The pseudocode of what I'm trying to do is:

if c is set:
    pass
else:
    c <- f(a, b)

where f is some function.

I tried the following

\documentclass[varwidth,margin=0.5cm]{standalone}
\usepackage{pgfkeys}

\pgfkeys{
    /mykeys/.is family, /mykeys,
    a/.estore in = \a,
    b/.estore in = \b,
    %c/.code={\pgfkeyssetvalue{c}{#1}\pgfkeysgetvalue{c}{\c}},
    c/.estore in = \c,
    default/.style = {
        a = hello,
        b = world,
    }
}

\newcommand{\mycommand}[1][]{%
    \pgfkeys{/mykeys, default, #1}
    \pgfkeysifdefined{c}{%if
        % pass
    }{%else
        \def\c{\a ,\ \b}
    }
    \c \\
}

\begin{document}    
    \mycommand[a=greetings]
    \mycommand[]
    \mycommand[c={howdy, stranger}] 
    \mycommand[]
    \mycommand[b=all]
\end{document}

But \pgfkeysifdefined{c} is never true.

output

So I tried

\documentclass[varwidth,margin=0.5cm]{standalone}
\usepackage{pgfkeys}

\pgfkeys{
    /mykeys/.is family, /mykeys,
    a/.estore in = \a,
    b/.estore in = \b,
    c/.code={\pgfkeyssetvalue{c}{#1}\pgfkeysgetvalue{c}{\c}},
    default/.style = {
        a = hello,
        b = world,
    }
}

\newcommand{\mycommand}[1][]{%
    \pgfkeys{/mykeys, default, #1}
    \pgfkeysifdefined{c}{%if
        % pass
    }{%else
        \def\c{\a ,\ \b}
    }
    \c \\
}

\begin{document}    
    \mycommand[a=greetings]
    \mycommand[]
    \mycommand[c={howdy, stranger}] 
    \mycommand[]
    \mycommand[b=all]
\end{document}

but once I call \mycommand with the c key set, then \mycommand uses the previous key values rather than using the default ones.

output

How can I test if the c key is provided and if it isn't, then set it based on other keys?

1 Answer 1

0

Isn't your code doing this already? All you need to do is to make the assignments local.

\documentclass[varwidth,margin=0.5cm]{standalone}
\usepackage{pgfkeys}

\pgfkeys{
    /mykeys/.is family, /mykeys,
    a/.estore in = \a,
    b/.estore in = \b,
    c/.code={\pgfkeyssetvalue{c}{#1}\pgfkeysgetvalue{c}{\c}},
    default/.style = {
        a = hello,
        b = world,
    }
}

\newcommand{\mycommand}[1][]{\begingroup%
    \pgfkeys{/mykeys, default, #1}
    \pgfkeysifdefined{c}{%if
        % pass
    }{%else
        \def\c{\a ,\ \b}
    }
    \c \\
    \endgroup
}

\begin{document}    
    \mycommand[a=greetings]
    \mycommand[]
    \mycommand[c={howdy, stranger}] 
    \mycommand[]
    \mycommand[b=all]
\end{document}

enter image description here

All I did was to add \begingroup and \endgroup.

Off-topic: consider using \par instead of \\.

You must log in to answer this question.

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