Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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}
}
share|improve this question
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 Answers 2

up vote 4 down vote accepted

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
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.