# How to create groups of table rows with alternating colors?

Problem. When coloring a table, using different colors for even / odd rows is quite usual and can be accomplished with the xcolor package. I, however, don't want to have alternating colors per row, but per row group.

Example. The following example is minimal working. I have a macro \writerow to output a table row (because much information in the original file is automatically generated), and I have a second macro \setgroup to set the group to 1 (white background) or 2 (gray background). To store this information, there is a macro \rc (reading "row color").

\documentclass{standalone}

\usepackage{ifthen}
\usepackage{colortbl}

\begin{document}

%
% Macros

\newcommand\rc{0.8}
\newcommand\setgroup[1]{
\ifthenelse{\equal{#1}{1}}{
\renewcommand\rc{1.0}
}{
\renewcommand\rc{0.8}
}
}
\newcommand\writerow[1]{
\\ \rowcolor[gray]{\rc} #1
}

%
% Data

\begin{tabular}{l}
\setgroup{1}
\writerow{Zeile 1}
\writerow{Zeile 2}
\setgroup{2}
\writerow{Zeile 3}
\writerow{Zeile 4}
\end{tabular}

\end{document}


Presumptions. The example works; however, every row is colored gray, which means that the \renewcommand\rc isn't working. Why?

Probably it's a problem of scope. But the only scope I can see in that document is that of the tabular environment, which shouldn't be a problem, as all the operations happen inside of it.

• Each cell of a table is a scope, so you need to make your commands global. use \gdef rather than \renewcommand – David Carlisle Mar 3 '12 at 12:14
Each cell of a table is a scope, so you need to make your commands global. use \gdef rather than \renewcommand as LaTeX doesn't offer a LaTeX-interface to global settings.
• @MartinSchröder \cs_new:Npn is possibly the nearest thing at the code level to this. (with some help in chat from @egreg and @JosephWright) – David Carlisle Mar 23 '12 at 22:47