考虑以下代码:
\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}
当第二次调用\newcommand
\ARROW
(\ARROW{2, 1}{left};
)时,代码会抱怨\coef
已经设计好了。
如何优化代码来规避这个问题?
答案1
为什么不使用钥匙?
\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}