tikz foreach index in variable name
Not sure I understand you correctly, but you can access the index of the loop with the count=\macro
option to the loop, e.g.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\noindent\foreach [count=\i] \x in {2,3,4,5,6} {%
cnt-\i = \x \\
}
\end{document}
I have no idea how to do what (I think) you're after with pgffor
. It is fairly easy to something kind of similar with Lua, but that requires of course compiling with lualatex
. I added an example below, where values are saved to a Lua table from a loop, and the \getcnt
command allows you to print a value from that table based on the index.
So another of my silly little Lua-examples, which may or may not be a complete waste of your time. Compile with lualatex
:
\documentclass{article}
\usepackage{luacode}
\newcommand{\getcnt}[1]{%
\luaexec{
tex.sprint(cnt[#1])
}}
\begin{document}
\begin{luacode}
cnt = {}
for i=1,10 do
cnt[i] = i^2 + 4
end
\end{luacode}
\getcnt{2} \getcnt{5}
\end{document}
I think what you are looking for is a list structure. Here is an example of a list in tikz. Note the double braces in the list definition. In addition, the list position index starts at 0, as with most programming languages. You can find a little more on lists in the tikz documentation in the section on syntax for math expressions.
\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\numbers{{1,3,5,2,4}}
\foreach \i in {0,...,4}{
\pgfmathsetmacro{\n}{\numbers[\i] + 4}
\draw[] (\i,0) -- (\i,\n);
}
\end{tikzpicture}
\end{document}
As mentioned in the comments if you want variable names with numbers refer to Defining commands/abbreviations that contain numbers.
Here is a way to do what you want with variable names that have an alphabetic prefix. You have to use \csname cnt\i\endcsname
to access the variable.
Since the foreach
loop is executed in a group, you have to use \global
if you want the effect of the \def
within the foreach
to be available after the \foreach
. See the difference after the first loop and the second loop.
\documentclass{article}
\usepackage{pgf}
\usepackage{pgffor}
\newcommand{\cntA}{1}
\newcommand{\cntB}{2}
\newcommand{\cntC}{3}
\newcommand{\cntD}{4}
\newcommand{\cntE}{5}
\begin{document}
\foreach \i in {A, B, ..., E} {
\pgfmathtruncatemacro{\temp}{\csname cnt\i\endcsname + 4}
\edef\csname cnt\i\endcsname{\temp}
}
\noindent
After 1st loop:\par
cntA = \cntA\par
cntB = \cntB\par
cntC = \cntC\par
cntD = \cntD\par
cntE = \cntE\par
\foreach \i in {A, B, ..., E} {
\pgfmathtruncatemacro{\temp}{\csname cnt\i\endcsname + 4}
\expandafter\global\expandafter\edef\csname cnt\i\endcsname{\temp}
}
\medskip
\noindent
After 2nd loop:\par
cntA = \cntA\par
cntB = \cntB\par
cntC = \cntC\par
cntD = \cntD\par
cntE = \cntE\par
\end{document}