1

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}]
Moriambar
  • 11,466
nunos
  • 1,019

1 Answers1

2

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}
Moriambar
  • 11,466
cmhughes
  • 100,947