1

Consider the following code:

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{etoolbox}
\begin{document}
\newcommand{\ARROW}[2]{
  \ifstrequal{#2}{left}{
    \newcommand{\coef}{-1}
  }{}
  \ifstrequal{#2}{right}{
    \newcommand{\coef}{1}
  }{};
  \coordinate(a) at (#1);
  \coordinate(b) at ($(a) + (\coef*2cm, 0)$);
  \draw[->](a) -- (b);
}
\begin{tikzpicture}
  \ARROW{1, 0}{right};
  \ARROW{2, 1}{left};
\end{tikzpicture}
\end{document}

When invoking the second time the \newcommand \ARROW (\ARROW{2, 1}{left};) the code complains that \coef is already designed.

How to optimise the code to circumvent this problem?

  • 1
    Add \newcommand\coef{} outside the definition and use \renewcommand or \def inside. – Ulrike Fischer Aug 8 '17 at 12:27
  • @Ulrike Fischer I checked. You can supply this an answer. – Viesturs Aug 8 '17 at 12:38
  • 1
    You can set \newcommand{\ARROW}[2]{{...}}. Then \coef will be local inside \ARROW. – StefanH Aug 8 '17 at 12:42
2

Why not using keys?

\documentclass[border=20]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}

\tikzset{
  /viesturs/right/.code=\def\ARROWCOEFF{+},
  /viesturs/left/.code=\def\ARROWCOEFF{-},
}

\newcommand{\ARROW}[2]{%
  \tikzset{/viesturs/#2}
  \coordinate(a) at (#1);
  \coordinate(b) at ($(a) + (\ARROWCOEFF 2cm, 0)$);
  \draw[->](a) -- (b);
}
\providecommand{\ARROWCOEFF}{}

\begin{document}

\begin{tikzpicture}
  \ARROW{1, 0}{right};
  \ARROW{2, 1}{left};
\end{tikzpicture}

\end{document}

enter image description here

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.