Macro to access a specific member of a list
To make the macro work both with inline lists and with lists in macros, you can use \edef
to assemble the loop command, with \noexpand
before every macro except for the arguments:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{xstring}
\begin{document}
% This works both with inline lists and with macros containing lists
\newcommand*{\GetListMember}[2]{%
\edef\dotheloop{%
\noexpand\foreach \noexpand\a [count=\noexpand\i] in {#1} {%
\noexpand\IfEq{\noexpand\i}{#2}{\noexpand\a\noexpand\breakforeach}{}%
}}%
\dotheloop
\par%
}%
\newcommand*{\MyList}{a1,b2,c3,d4,e5}%
This should print "b": \GetListMember{a,b,c,d,e}{2}%
This should be blank: \GetListMember{a,b,c,d,e}{6}%
This should be "a1": \GetListMember{\MyList}{1}%
This should be "c3": \GetListMember{\MyList}{3}%
This should be blank: \GetListMember{\MyList}{6}%
\end{document}
You can use \StrBetween
and your code does not require calc or pgf:
\documentclass{article}
\usepackage{xstring}
\begin{document}
% This works both with inline lists and with macros containing lists
\newcommand*\GetListMember[2]{\StrBetween[#2,\number\numexpr#2+1]{,#1,},,\par}%
\newcommand*\MyList{a1,b2,c3,d4,e5}
This should print "b": \GetListMember{a,b,c,d,e}{2}
This should be blank: \GetListMember{a,b,c,d,e}{6}
This should be "a1": \GetListMember{\MyList}{1}
This should be "c3": \GetListMember{\MyList}{3}
This should be blank: \GetListMember{\MyList}{6}
\end{document}
The macro \mypkg_expand:Nw
expands or not the argument of a function depending on whether it is unbraced, or braced. The \GetListMember
is just defined through that macro, and \GetListMember_aux:nn
recieves the list (expanded once) as a first argument and the index as a second. Now \clist_item:nn
starts counting at 1. Negative arguments start from the right, but require a recent version of the expl3
package.
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\cs_new_protected_nopar:Npn \mypkg_expand:Nw #1
{
\peek_catcode_ignore_spaces:NTF \c_group_begin_token
{ #1 } { \exp_args:NV #1 }
}
\cs_new_nopar:Npn \GetListMember
{ \mypkg_expand:Nw \GetListMember_aux:nn }
\cs_new_nopar:Npn \GetListMember_aux:nn #1 #2
{
\clist_item:nn {#1} {#2}
\par
}
\ExplSyntaxOff
\begin{document}
\newcommand*{\MyList}{a1,b2,c3,d4,e5}
This should print ``b'': \GetListMember{a,b,c,d,e}{2}%
This should be blank: \GetListMember{a,b,c,d,e}{6}%
This should be ``a1'': \GetListMember\MyList{1}%
This should be ``c3'': \GetListMember\MyList{3}%
This should be blank: \GetListMember\MyList{6}%
\smallskip
This should print ``b'': \GetListMember{a,b,c,d,e}{-4}%
This should be blank: \GetListMember{a,b,c,d,e}{-6}%
This should be ``a1'': \GetListMember\MyList{-5}%
This should be ``c3'': \GetListMember\MyList{-3}%
This should be blank: \GetListMember\MyList{-6}%
\end{document}