# Can't use caption in new environment

I am trying to make some consistent tables and looked into the nenenvironmentcommand. However, I am having trouble having a caption and using the defined environment at the same time.

newenvironment definition:

\newenvironment{mytable}[1]
{
\begin{table}[ht]
#definitions go here
\begin{tabular}{#1}
}
{
\end{tabular}
\end{table}
}


If I have this, I get no error, and everything works ok:

\begin{mytable}{ccc}
cell & cell & cell \\
\end{mytable}


However, if I just add the \caption command like this:

\begin{mytable}{ccc}
cell & cell & cell \\
\caption{caption}
\end{mytable}


I get this error:

Missing \endgroup inserted. [\caption{caption}]

-
You're including the caption in the tabular environment, which is not allowed. – egreg Mar 17 '13 at 0:45
Ok, that makes sense. Any possible workaround? – nunos Mar 17 '13 at 0:45
I don't think you gain anything with such an environment. You just spare \begin{tabular} and \end{tabular}, losing in flexibility. – egreg Mar 17 '13 at 0:47

Here's a way that you define your environment, borrowing some code from What is the difference between \empty and \@empty?

\newenvironment{mytable}[2][]{%
\begin{table}[ht]
%definitions go here
\if\relax\detokenize{#1}\relax
\else
\caption{#1}
\fi
\centering
\begin{tabular}{#2}
}
{%
\end{tabular}
\end{table}
}


It takes one mandatory argument (the alignment, such as ccc), and one optional argument, which is the caption. It can be used as

\begin{mytable}[caption]{ccc}


or

\begin{mytable}{ccc}


I'm not convinced this is a good idea though- you can probably just about use label still, but it seems unnatural. One of the other things that won't be easy to solve is that the caption command takes an optional argument that writes to the lof. You could probably solve this using the xparse package, but all of this for something that was supposed to save time :)

\documentclass{article}

\newenvironment{mytable}[2][]{%
\begin{table}[ht]
%definitions go here
\if\relax\detokenize{#1}\relax
\else
\caption{#1}
\fi
\centering
\begin{tabular}{#2}
}
{%
\end{tabular}
\end{table}
}

\begin{document}

\begin{mytable}[caption]{ccc}
1   &   2   &   3   \\
\end{mytable}
\end{document}

-