[Tex/LaTex] Using \columncolor outside column definition

tables

I'm trying to create a command, which calls on an environment, which defines a custom column definition with one argument using \newcolumntype, and defines a second command, containing parameters for a table column. Then, still within the first command, I begin the tabular environment and call the custom column, with the second command as its argument. I always get an undefined control sequence error, though. Any thoughts on why that might be?

I'm sure that was clear as mud, but I've cut it down to a minimal example, which follows:

\documentclass{article}
\usepackage{array}
\usepackage[table,dvipsnames]{xcolor}
\usepackage{colortbl}

\newenvironment{tablecolor}{
    \newcommand{\tlight}{\columncolor{SkyBlue!30}\color{black}}
    \newcolumntype{C}[1]{>{##1}c}
}{}

\newcommand{\tablegoals}{
\begin{tablecolor}
\begin{tabular}{l|C{\tlight}}
Goal 7  & \\
\end{tabular}
\end{tablecolor}
}

\begin{document}
    \tablegoals
\end{document}

Here's my second attempt. Different approach, same undefined control sequence error with \columncolor.

\documentclass{article}
\usepackage{array}
\usepackage[table,dvipsnames]{xcolor}
\usepackage{colortbl}
\usepackage{ifthen}

\newenvironment{tablecolor}{
    \newcolumntype{C}[1]{>{
        \ifthenelse{\equal{dark}{##1}}{
            \columncolor{Cyan}\color{white}
            }{
            \columncolor{SkyBlue!30}\color{black}
        }
    }c}
}{
}

\newcommand{\tablegoals}[1]{
    \begin{tablecolor}
        \begin{tabular}{l|C{dark}}
            Goal 7  &   #1
        \end{tabular}
    \end{tablecolor}
}

\begin{document}
    \tablegoals{Check mark}
\end{document}

Best Answer

I asked David Carlisle, who wrote both the colortbl package and \newcolumntype in the array package about this problem. Here's his response:

the error message is telling you that \columncolor is not defined and in fact looking at colortbl.sty there is no definition for such a command, it is just used as a token in

\expandafter\CT@extract\the\toks\@tempcnta\columncolor!\@nil

which means essentially that after the normal array package table processing has done its stuff, colortbl goes in finds that token as a marker and inserts some extra stuff.

I can't remember why it was written that way (the log says it's 15 years ago:-) but probably there was a reason at the time.

The result (which is probably not documented too well) is that if you hide \columncolor in a macro it won't work, it has to be there explicitly at the top level. You could use newcolumntypes defining one color or the other, or taking a parameter taking the colour, as they are expanded out by array.sty before colortbl starts looking for its tokens.