7

I'm defining new environment and I'm trying to pass to it two arguments:

\newenvironment{ctable}[2]%
{%
\begin{center}%
    \begin{tabular}{#1}%
}%
{%
    \end{tabular}%
 \captionof{table}{#2}%
\end{center}%
}

Problem is with a second parameter (captionof), it isn't working. Is there a nice way to make it work? I'm aware that captionof could/should be after \begin{center} or before it, but I need it to be below the table. In short: first argument defines table, second defines caption of the table.

Thank you.

1

3 Answers 3

12

The trick storing the second parameter as macro and using it in the "end" part of the environment:

\newenvironment{ctable}[2]%
{%
  \def\ctablecaption{#2}%
\begin{center}%
    \begin{tabular}{#1}%
}%
{%
    \end{tabular}%
 \captionof{table}{\ctablecaption}%
\end{center}%
}
2
  • 1
    Nice trick. ;)
    – aksr
    Jun 25, 2013 at 21:02
  • This is what I was looking for. :)
    – aksr
    Jun 25, 2013 at 21:06
9

Using the environ package you can avoid the standard trick illustrated in Heiko's answer:

\documentclass{article}
\usepackage{capt-of}
\usepackage{environ}

\NewEnviron{ctable}[2]%
{%
\begin{center}%
    \begin{tabular}{#1}%
    \BODY
    \end{tabular}%
 \captionof{table}{#2}%
\end{center}%
}

\begin{document}

\begin{ctable}{cc}{test}
test & test
\end{ctable}

\end{document}
1
  • Thank you!, I didn't know about this package, I'll try it. ;)
    – aksr
    Jun 25, 2013 at 21:04
9

You're trying to avoid floating tables, which is quite dangerous. Moreover you lose flexibility. However, if you really want to shoot yourself in the foot ;-), here's a possibility: the package xparse.

\documentclass{article}
\usepackage{xparse,capt-of}

\NewDocumentEnvironment{ctable}{mm} % two arguments in braces
 {% begin part
  \begin{center}
  \begin{tabular}{#1}
 }
 {% end part
  \end{tabular}
  \captionof{table}{#2}
  \end{center}
 }

\begin{document}
\begin{ctable}{ll}{A meaningful caption\label{tab:foo}}
A & B \\
C & D
\end{ctable}
\end{document}
1
  • I was aware of xparse package, just thought to try without it. Thank you egreg. ;)
    – aksr
    Jun 25, 2013 at 21:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .