4

I want to create an array containg specific values of a counter to be used in a foreach loop. So I want to define a command that adds the actual counter value at the end of the list. What I can do is:

\documentclass{standalone}
\usepackage{pgfmath,pgffor}
\begin{document}
\def\names{{"Katie","Frank","Laura","Joe"}}%
\newcounter{lines}%
\setcounter{lines}{3}%
\def\arr{1,\arabic{lines}}%

\foreach \i in \arr {%
  Name \i: \pgfmathparse{\names[\i]}\pgfmathresult, }

\end{document}

But what I need is an empty list arr and a function that I can use to fill arrwith values of lines like e.g. \addtoarr{\arabic{lines}}.

I tryed using the lstdock package like:

\let\arr\@empty

\def\addtolist#1#2{%
  \lst@lAddTo#1{#2}}

\addtolist{\arr}{\arabic{lines}}

But this gives me an error I don't understand.

PeMa
  • 175
  • 7

2 Answers2

4

There are differents methods, here is one

\documentclass{article}
\usepackage{pgfmath,pgffor}
\begin{document}
\def\names{{"Katie","Frank","Laura","Joe"}}%
\newcounter{lines}%
\setcounter{lines}{1}%

\newcommand*\arr{}%
\newcommand{\mtadd}{%
\ifx\arr\empty
\edef\arr{\arabic{lines}}
\else\edef\arr{\arr,\arabic{lines}}
\fi}

\mtadd
\setcounter{lines}{3}%
\mtadd
\foreach \i in \arr {%
  Name \i: \pgfmathparse{\names[\i]}\pgfmathresult, }

\end{document}
touhami
  • 19,520
1

If you're just interested in spitting out some contents of a list, perhaps the following might be of interest:

enter image description here

\documentclass{article}
\usepackage{etoolbox}

\newcommand{\listsep}{, }
\makeatletter
\newcommand{\@insertlistsep}{}
\newcounter{@listname}
\newcommand{\addtolist}[1]{%
  \stepcounter{@listname}% Add one person to counter
  \expandafter\@namedef\expandafter{@listnames:\the@listname}{#1}}% Define counter-based name
\newcommand{\printlist}[1]{%
  \renewcommand{\@insertlistsep}{\renewcommand{\@insertlistsep}{\listsep}}% https://tex.stackexchange.com/a/89187/5764
  \renewcommand*{\do}[1]{\@insertlistsep Name~##1: \textbf{\@nameuse{@listnames:##1}}}% How each item will be processed
  \docsvlist{#1}}% Process list
\makeatother

\begin{document}

\addtolist{Katie}% 1
\addtolist{Frank}% 2
\addtolist{Laura}% 3
\addtolist{Joe}% 4

\printlist{1,2}

\printlist{}

\printlist{1,3,4}

\printlist{3,3,3}

\end{document}

Additional work, if required, would be to build in a \clearlist feature, as well as some error-checking to make sure you don't access elements outside the list.

List processing is discussed in How to iterate over a comma separated list?

Werner
  • 603,163