For a package, I want to write code that creates tables, where the exact type of table is configurable (tabular
, longtable
, tabularx
, ... [Update: David rightly remarked that formats like tabularx
would be harder to use in a configurable way, as they need more parameters]), and where the number of columns is determined by the program (so table specs like l|l
are computed; details do not matter here). The following simple code works with LaTeX tables:
\def\mytablespec{l|l}
\def\mytabletype{tabular}
\begin{\mytabletype}{\mytablespec}
1 & 2 \\\hline
3 & 4 \\
\end{\mytabletype}
However, if the package array
is loaded, the code fails with the error
Package array Error: Illegal pream-token (\mytablespec): `c' used.
The problem is that array
does not expand table specs. One can force this as follows:
\def\mytablespec{l|l}
\expandafter\tabular\expandafter{\mytablespec}
1 & 2 \\\hline
3 & 4 \\
\endtabular
This code works with or without the array
package. However, this code no longer uses a command to define the table type. I did not manage to combine \expandafter
with \begin{\mytabletype}...\end{\mytabletype}
. The following, however, seems to work:
\expandafter\csname\expandafter\mytabletype\expandafter\endcsname\expandafter{\mytablespec}
1 & 2 \\\hline
3 & 4 \\
\csname end\mytabletype\endcsname
[Update: David pointed out that the following simpler version also works:
\csname\mytabletype\expandafter\endcsname\expandafter{\mytablespec}
1 & 2 \\\hline
3 & 4 \\
\csname end\mytabletype\endcsname
]
Besides being quite ugly, this assumes that environments like tabular
and longtable
always provide two corresponding commands, such as \tabular
and \endtabular
. This seems to be the case for many packages, but I could not find out if there is a general reason why this should be the case.
Is this the right way to solve this problem? Is there a cleaner/easier solution? In general, the behaviour of tables changes quite a bit if array
is loaded (it also modifies table width computation in incompatible ways); is there maybe a more general approach to make packages robust against such things?