1

For an illustration, see the following MWE.

MWE

\documentclass{article}
\usepackage{etoolbox}

\newcommand\Push[1]{\gappto\Array{#1}}


\newcommand\NewItem[2]{%
    \expandafter\newrobustcmd\csname#1\endcsname{#2}%
    \Push{#1}%
}

\newcommand\PrintOut{%
 % for each <x> in \Array, call \<x>
}

\NewItem{Books}{There are 3 books in stock.}
\NewItem{Pencils}{There are 2 pencils in stock.}

\begin{document}
\section{Manually printed}
\begin{enumerate}
    \item \Books
    \item \Pencils
\end{enumerate}

\section{Automatically printed by iterating \textbackslash Array}
\end{document}

Questions

How to iterate the list \Array and call the corresponding macro for each element?

Display Name
  • 46,933

1 Answers1

3

This is a perfect candidate for expl3 property lists.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\prop_new:N \l_yasashii_items_prop

\NewDocumentCommand \AddItem { m m }
 {
  \prop_put:Nnn \l_yasashii_items_prop { #1 } { #2 }
 }

\NewDocumentCommand \GetItem { m }
 {
  \prop_get:Nn \l_yasashii_items_prop { #1 }
 }

\NewDocumentCommand \PrintList { }
 {
  \begin{enumerate}
   \prop_map_inline:Nn \l_yasashii_items_prop
    { \item ##2 }% <- #1 is key, #2 is value
  \end{enumerate}
 }

\ExplSyntaxOff

\begin{document}
\AddItem{Books}{There are 3 books in stock.}
\AddItem{Pencils}{There are 2 pencils in stock.}
\GetItem{Books}
\PrintList
\end{document}

enter image description here

Henri Menke
  • 109,596
  • Not really a property list, because the mapping is not guaranteed a specific order. – egreg Dec 07 '15 at 08:44
  • @egreg Since the items are key-value pairs I figured that the order didn't matter. Otherwise, I'd use seqs to store keys and values separately. – Henri Menke Dec 07 '15 at 08:49