How to use variables inside a command when generating a table?

In comments, the reason is pointed out: & besides other things ends and begins a group so the definition of \secondPoint is forgotten. Solution: use \gdef :

\documentclass[]{article}
\begin{document}

\newcommand\rowdata[2]{%
    \gdef\firstPoint{#1}%
    \gdef\secondPoint{#2}%
    \createRow
    % #1 & #2 \\ would work.
}
\newcommand\createRow{ %
    \wlog{\firstPoint \secondPoint} % it appears in the log 
    \firstPoint & \secondPoint \\ % this fails
}

\begin{table}
    \begin{tabular}{l l}
        \rowdata{a}{b}
        \rowdata{d}{b}
        \rowdata{a}{c}
    \end{tabular}
\end{table}
\end{document}

The stringstrings package has a \getargs command that works like Unix. It will parse a single argument into \argi, \argii, etc. The total number of arguments is in \narg.

\documentclass{article}
\usepackage{stringstrings}
\begin{document}
\getargs{1 2 3 4 5 6 7 8 9 10 11 12 FinalArgument}
There are \narg~arguments.  The thirteenth is \argxiii
\end{document}

The result to this example is:

There are 13 arguments. The thirteenth is FinalArgument

======

In answer to a request for a MWE, I note that stringstrings did suffer the same problem the user noticed above, which is that the getargs results were not global. However, I remedy that here with a \makeatletter redefinition of \getargs.

Then I redefined \rowdata to take one big space-separated argument. So here is how one prints a 12 column table with a command that generates the rows. Furthermore, the argument is merely space-separated data, not separate {} blocks.

AFTERTHOUGHT: The \rowdata command can take more than just typed data as its content. For example, you could have \today as part of the data, and it would take up three arguments (i.e., columns) of the table

Here is the code

\documentclass[]{article}
\usepackage{stringstrings}
\makeatletter
\renewcommand\getargs[2][q]{\+%
  \if v#1\def\@mode{q}\else\def\@mode{#1}\fi
  \edef\@argv{#2}%
  \@getstringlength{\@argv}{@stringsize}%
  \setcounter{@iargc}{0}%
  \whiledo{\value{@stringsize} > 0}{%
    \addtocounter{@iargc}{1}%
    \getaword[\@mode]{\@argv}{1}%
    \expandafter\global\expandafter\edef\csname arg\roman{@iargc}\endcsname{\thestring}%
    \removeword[e]{\@argv}%
    \edef\@argv{\thestring}%
    \@getstringlength{\@argv}{@stringsize}%
  }
  \edef\narg{\arabic{@iargc}}%
\?}
\makeatother
\newcommand\rowdata[1]{%
  \getargs{#1}
  \argi & \argii & \argiii & \argiv & \argv & \argvi & \argvii & 
  \argviii & \argix & \argx & \argxi & \argxii \\    }
\begin{document}
\begin{table}
    \begin{tabular}{l l l l l l l l l l l l}
        \rowdata{a b 3 4 5 6 7 8 9 10 11 12}
        \rowdata{d b blah 3 45 89 s rt 343 \today}
        \rowdata{a c 45 dfgf 454 454 fd 7 sds ssd s s}
    \end{tabular}
\end{table}
\end{document}

enter image description here

Tags:

Macros

Tables