[Tex/LaTex] How to use \def or similar command to store an arbitrary number of variables for later processing

macrosprogramming

I'm trying to create a package for drawing simple sequence diagrams using PGF/TikZ. Here is the basic idea I'm stuck at (not the whole idea to make it short):

Let's say we have 1 environment (say myseqdiag) & 1 command (say createobject) in this package.

The user would use these as follows:

\begin{myseqdiag}
\createobject{my name is A} 
\createobject{my name is B}
  %<here, other calls to createobject>
\end{myseqdiag}

Calling the command createobject causes a counter objcounter to be incremented, and would store #1 (hopefully) in a variable called obja (if there is such thing as "variable" in TeX/LaTeX).

At the environment end, the code should use the final count and use the stored "variables" ("my name is A", "my name is B"….) in drawing the objects (lifelines).

The problem is that I'm not able to store these parameters.

I tried

\def\obj\alph{objcounter}{#1}

inside the code of createobject, hoping that it would define obja, objb, …, but it's not working.

I also tried other variations that did not work.

I'm newbie to LaTeX, and I'm missing the concept of variables & arrays as in programming languages. So is there a solution to my problem?

Thanks in advance for any help.

Best Answer

I'm missing the concept of variables & arrays as in programming languages...

TeX allows you to define your own data structures and associative arrays are sort of built-in. You can think of macros as associative arrays.

Normally a task like the one you are describing I would tackle it as a two step approach.

First you define a list for example \def\alist{foo,bar,beer}

Secondly when you define a command with one of the automatic ways described by the other posters you add the name onto the list as well.

This way you can iterate over the list and effectively you have created an array of objects. See the minimal below.

   \documentclass{article}
    \usepackage{pgfplots}
    \begin{document}
    \makeatletter
    \gdef\alist{john,}
    \def\addtolist#1#2{\g@addto@macro{#1}{#2,}}
    \def\CommandFactory#1#2{%
      \expandafter\def\csname#1\endcsname{#2}
      \addtolist{\alist}{#1}
    }
    \CommandFactory{George}{George's commands}
    \CommandFactory{Mary}{Mary's commands}
    \CommandFactory{foo}{foo commands}
    \CommandFactory{bar}{\tikzpicture
        \axis[stack plots=y]
        \addplot coordinates
            {(0,1) (1,1) (2,2) (3,2)};
        \addplot coordinates
            {(0,1) (1,1) (2,2) (3,2)};
        \addplot coordinates
            {(0,1) (1,1) (2,2) (3,2)};
        \endaxis
    \endtikzpicture}

    %loop through all the records
    \@for \i:=\alist \do{%
      \@nameuse{\i}

    }

    \makeatother
    \end{document}

I have kept the code to the bare minimum to make it more clear.

Related Question