# Passing variable as argument

I need to pass a variable to a command, but I cannot get it to work. Here is a short example that shows that #1 can be sent to a command, but not a variable that is a copy of #1. Why is this?

\documentclass{article}
\usepackage{tikz}

\pgfkeys
{ /mypgf/.cd
, options/.store in = \options
, options/.get = \options
}

\newcommand{\img}[2][]{
\pgfkeys{/mypgf/.cd, options=#1}
\def \test {#1}

% This works:
\includegraphics[#1]{#2}

% This does not work:
\includegraphics[\options]{#2}

% This does not work either:
\includegraphics[\test]{#2}
}

\begin{document}

\img[width=0.1\textwidth]{image.png}

\end{document}

• Welcome to TeX.SX! \includegraphics does not expand its first argument. Mar 2 '14 at 15:33

As mentioned in @egreg's comment, \includegraphics does not expand its first argument. A judicious use of \expandafter resolves that part of the problem.

But also, \pgfkeys is getting confused by the = buried within the value you're passing. Try something like:

\documentclass{article}
\usepackage{tikz}

\pgfkeys
{/mypgf/.cd,
options/.store in = \options,
options/.get = \options,
}

\newcommand{\img}[2][]{
\pgfkeys{/mypgf/.cd, options={#1}}
\def \test {#1}
%%\typeout{===>"\options"|#1}%%

% This works:
\includegraphics[#1]{#2}

% This does not work:
\expandafter\includegraphics\expandafter[\options]{#2}

% This does not work either:
\expandafter\includegraphics\expandafter[\test]{#2}
}

\begin{document}

\img[width=\dimexpr0.1\textwidth]{example-image}

\end{document}


By uncommenting \typeout you can better see what's being passed to \options as you wrote it. By wrapping #1 in brackets, \options receives the correct string.

Also, I would put the commas, from within \pgfkeys{....}, at the end of the lines to prevent unwanted white space creeping into the values of your keys.

• Sweet! Thanks :) But nothing seemed to happen when I uncommented the \typeout Mar 2 '14 at 17:26
• \typeout writes to the terminal and your log file. It's not that important and not necessary for your fix. It's just useful sometimes when trying to debug something. I put the ===> to make it stand out a bit more on the command line. If you're not compiling from the command line, then you can always look in the log file. Mar 2 '14 at 17:32