[Tex/LaTex] Using an array element to specify end iteration point in TikZ “\foreach”

foreachpgfmathtikz-pgf

Is it possible to access an array and use one of its elements to specify the last iteration point in a TikZ \foreach?

I've tried with the code below but I keep getting a compilation error:

! Argument of \pgffor@@dotscharcheck has an extra }.
<inserted text>
                \par
l.49   }

And here's a minimal example:

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{positioning}

\begin{document}

\begingroup
\newdimen\bitSize
\bitSize=2mm
\newdimen\bitSep
\bitSep=0.5mm
\newdimen\bitBigSep
\bitBigSep=3mm
\begin{tikzpicture}[%
    auto,
    every node/.style={%
      node distance=0pt,
    },
    bit/.style={%
      draw,
      rectangle,
      minimum size=\bitSize,
      inner sep=0pt,
      node distance=\bitSep,
    },
  ]

  \def\numBits{{4, 8, 4}}
  \foreach \i in {1, 2, 3} {%
    \pgfmathtruncatemacro\prevI{\i-1}
    \foreach \j in {1, ..., \numBits[\prevI]} {%
      \pgfmathtruncatemacro\prevJ{\j-1}

      % Draw bit
      \ifnum \j=1
        \ifnum \i=1
          \node [bit] (bit\i-\j) {};
        \else
          \node [bit, right=\bitBigSep of bit\prevI-\numBitsArray[\prevI-1]]
            (bit\i-\j) {};
        \fi
      \else
        \node [bit, right=of bit\i-\prevJ] (bit\i-\j) {};
      \fi
    }
  }
\end{tikzpicture}
\endgroup

\end{document}

Best Answer

For anyone interested, here's how I solved it:

\documentclass{standalone}

\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{positioning}

\begin{document}

\begingroup
\newdimen\bitSize
\bitSize=2mm
\newdimen\bitSep
\bitSep=0.5mm
\newdimen\bitBigSep
\bitBigSep=3mm
\begin{tikzpicture}[%
    auto,
    every node/.style={%
      node distance=0pt,
    },
    bit/.style={%
      draw,
      rectangle,
      minimum size=\bitSize,
      inner sep=0pt,
      node distance=\bitSep,
    },
  ]

  \def\numBitsList{4, 16, 4}
  \def\numBitsArray{{\numBitsList}}
  \foreach \n [count=\i] in \numBitsList {%
    \pgfmathtruncatemacro\prevI{\i-1}
    \pgfmathparse{\numBitsArray[\prevI]} \let\numBits\pgfmathresult
    \foreach \j in {1, ..., \numBits} {%
      \pgfmathtruncatemacro\prevJ{\j-1}

      % Draw bit
      \ifnum \j=1
        \ifnum \i=1
          \node [bit] (bit\i-\j) {};
        \else
          \pgfmathparse{\numBitsArray[\prevI-1]} \let\pprevJ\pgfmathresult
          \node [bit, right=\bitBigSep of bit\prevI-\pprevJ]
            (bit\i-\j) {};
        \fi
      \else
        \node [bit, right=of bit\i-\prevJ] (bit\i-\j) {};
      \fi
    }
  }
\end{tikzpicture}
\endgroup

\end{document}