4

I am trying to define a new table environment with optional caption. However, if I don't pass it the caption, I am still getting the "Table 1.1:" below the table. What am I missing here? Thanks. Examples below.

If I call it like this, it works as supposed.

\begin{mytable}[This is the caption]
% table content goes here
\end{mytable}

But if I call it like this, I get the "Table 1.1:" but nothing after. In the case with no caption provided, I obviously would like for the "Table 1.1:" not to appear.

\begin{mytable}
% table content goes here
\end{mytable}

newenvironment definition:

\def\mycaption{\relax}
\newenvironment{mytable}[1][]
{
    \if\relax\detokenize{#1}\relax
    \gdef\mycaption{\relax}
    \else
    \gdef\mycaption{#1}
    \fi
    \begin{table}[ht]
        \centering
            \begin{tabular}{lccc}
                & \textbf{\vocalsn} & \textbf{\nonvocalsn} & \textit{Totals} \\
                \hline
}
{
                \hline
            \end{tabular}
        \caption{\mycaption}
        \fi
    \end{table}
}
Moriambar
  • 11,466
nunos
  • 1,019
  • 1
    didn't I already answer this in Can't use caption in new environment ? :) – cmhughes Mar 18 '13 at 15:42
  • It's very similar yes, but it has the difference that I would like a environment with only 1 optional argument whereas your answer in that other question if for 1 mandatory and 1 optional argument. Basically, my code is adapted from yours to achieve that desired result. But for some reason, I am not getting it. If you would care to take a look. Thanks. – nunos Mar 18 '13 at 15:46

2 Answers2

4

you always execute \caption so you will always get a caption even if the text of the caption is empty. Put the call to \caption into the redefinition of \mycaption, e.g.,

...
  \gdef\mycaption{}%
\else
  \gdef\mycaption{\caption{#1}}%
\fi
...
\mycaption
3

A bit simpler with xparse:

\usepackage{xparse}
\NewDocumentEnvironment{mytable}{ o }
 {\begin{table}[ht]
  \centering
  \begin{tabular}{lccc}
    & \textbf{\vocalsn} & \textbf{\nonvocalsn} & \textit{Totals} \\
  \hline}
 {\hline
  \end{tabular}
  \IfValueT{#1}{\caption{#1}}
  \end{table}}

With xparse you can use the arguments also in the "end part"; the condition \IfValue... is true only if the optional argument is specified, so with

\IfValueT{#1}{\caption{#1}}

you insert the caption only if the optional argument is actually expressed.

Moriambar
  • 11,466
egreg
  • 1,121,712