One of the answers to a question about how to calculate the length of a PGF array provided a function that increments a counter for each step of the iteration on the array provided as its argument.
But if I store an array in a variable with \def\myarray{{1,2,3,4,5,6}} and then use \arrayLength{\myarray}, the number 1 is output, instead of 6. I believe it's got something to do with how \myarray is expanded, but can't understand what. \expandafter\arrayLength{\myarray} also outputs 1.
How can a function \len correctly output the number of elements in an array, no matter if it is \len{{1,2,3}} or \len{\myarray}?
A MWE:
\documentclass[tikz]{standalone}
\newcounter{arraycard}
\def\arrayLength#1{%
\setcounter{arraycard}{0}%
\foreach \x in #1{%
\stepcounter{arraycard}%
}%
\the\value{arraycard}%
}
\begin{document}
The length of $\{1,2,3\}$ is \arrayLength{{1,2,3}}.
The length of $\{1,2,\{3,4\},5\}$ is \arrayLength{{1,2,{3,4},5}}.
\def\myarray{{1,2,3,4,5,6}}
The length of \verb|\myarray| is \arrayLength{\myarray}.
\end{document}




\def\myarray{1,2,3,4,5,6}instead it works as expected. The reason is that it just counts the array as one item. – Jun 13 '19 at 18:09\expandafter\arrayLength{\myarray}expands{but that isn't expandable, you want\expandafter\arrayLength\expandafter{\myarray}– David Carlisle Jun 13 '19 at 18:09\arrayLength, but always using\arrayLength{{1,2,3,4,5,6}}and\expandafter\arrayLength\expandafter{\myarray}? That is, the function has 2 usages, depending on whether its argument is a macro? – Daniel Diniz Jun 13 '19 at 18:13\expandafter\arrayLength\expandafter{\myarray}does is it expands\myarraybefore\arrayLengthreads its argument, so what\arrayLengthsees is in either case\arrayLength{{1,2,3,4,5,6}}. – Skillmon Jun 13 '19 at 18:22