7

Assume I want to perform a complicated calculation within a TikZ key defintion. What is the recommended way to do this?

Reading through the manual and digging around in other questions led me to believe that the solution might look somewhat like this:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\tikzset{mykey/.style args={#1,#2,#3}{mykey/.code={%
      % perform complicated calculation involving #1, #2 and #3 here
      \def\x{5}
    },
    scale=\x
}}

\begin{tikzpicture}[mykey={1,2,3}]
  \draw[->] (0,0) -- (1,0);
\end{tikzpicture}

\end{document}

However, this doesn't work:

! Undefined control sequence.
<argument> \x 

How do I do this properly?

2
  • \x should probably be global.. Commented Dec 16, 2014 at 21:04
  • 1
    define another key with /.store in handler and use that in the code or use \pgfkeysgetvalueof and define the value as such.
    – percusse
    Commented Dec 16, 2014 at 21:20

1 Answer 1

12

Here is an example how you can do this :

\documentclass[varwidth,border=10]{standalone}
\usepackage{tikz}

\begin{document}

\tikzset{
  mykey/.code args={#1,#2,#3}{
    % perform complicated calculation involving #1, #2 and #3 here
    % for example
    \pgfmathparse{(#2-#1)*#3}
    \pgfkeysalso{/tikz/scale=\pgfmathresult}
  }
}

\begin{tikzpicture}
  \draw[->, mykey={1,2,3}] (0,0) -- (1,0);
  \draw[->, thick, red] (0,0) -- (1,0);
\end{tikzpicture}

\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 .