这是我创建的,但是我如何才能访问\n
foreach 循环之外的循环变量,以便我可以像这样写:
\n = \n + 1 % this is definitely not right, and it seems I couldn't reference \n outside foreach loop
\node[element,fill=white,xshift=\n*1cm](l_N\n){...};
而不是对值进行硬编码。
这是完整的代码:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,calc}
\begin{document}
\begin{tikzpicture}[remember picture,
element/.style={rectangle,draw,fill=red!20,minimum width=1cm,minimum height=1cm},
outer/.style={circle,draw=green,fill=green!20,thick,inner sep=10pt,minimum size=7cm}
]
\node[outer,draw=green] (A) {
\begin{tikzpicture}
\foreach \i [count=\n] in {0, 1, ..., 3}
\node[element,xshift=\n*1cm](l_N\n){\i};
\node[element,fill=white,xshift=5*1cm](l_N5){...};
\node[element,xshift=6cm](l_N9){9};
\end{tikzpicture}
};
\node[outer,draw=green,right=of A] (B) {
\begin{tikzpicture}
\foreach \i [count=\n] in {0, 1, ..., 3}
\node[element,xshift=\n*1cm](r_N\n){\i};
\node[element,fill=white,xshift=5*1cm](r_N5){...};
\node[element,xshift=6cm](r_N9){9};
\end{tikzpicture}
};
\draw[thick,dashed] (l_N9) -- (r_N1);
\end{tikzpicture}
\end{document}
结果:
答案1
一种方法是将值保存在全局中:
代码:
\documentclass{article}
\usepackage{tikz}
\newcommand*{\LastLoopValue}{No value}
\begin{document}
\foreach \i [count=\n] in {0, 2, ..., 14} {
\i,
\xdef\LastLoopValue{\n}%
}
Outside of loop, count=\LastLoopValue
\end{document}
答案2
循环\foreach
是一个很棒的工具,但它具有在组内创建和运行的特殊性。因此,受范围限制的每个操作( \def
、 、...)都不会在循环之外存活。\clip
在某些情况下,知道还有其他循环不在组中运行是有益的。例如xint 束有这样的循环。下面是一个例子:
\documentclass[preview, border=7mm]{standalone}
\usepackage{xinttools}
\newcommand*{\LastLoopValue}{No value}
\newcounter{loopCounter}
\begin{document}
\xintFor* #1 in {\xintSeq[2]{0}{14}} \do{
#1, \def\LastLoopValue{#1}
\stepcounter{loopCounter}
}
... outside of loop, LastLoopValue=\LastLoopValue, loopCounter=\arabic{loopCounter}
\end{document}