1

I looked into this answer and tried to improve it. My goal is to get this table:

| 1 |
| 2 |
| 3 |

But instead I get this:

| 1 |
| 1 |
| 1 |

Code:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgffor}
\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\global\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand*\resettabtoks{\global\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}
\makeatother
\begin{document}
\resettabtoks
\foreach \i in {1,...,3} {%
  \addtabtoks{\i \\\hline}
}

\begin{tabular}{ | c | }
  \hline
  \printtabtoks
\end{tabular}
\end{document}

I think, it's caused by \expandafter, but I don't know, how to fix it.

user4035
  • 5,035
  • 6
  • 40
  • 57
  • I added code to my answer for coping with your problem and also the one in your other question – egreg Jul 26 '16 at 09:47

1 Answers1

2

you want to add the expansion of \i not the token \i so

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{pgffor}
\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\global\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand*\resettabtoks{\global\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}
\makeatother
\begin{document}
\resettabtoks
\foreach \i in {1,...,3} {%
  \expandafter\addtabtoks\expandafter{\i \\\hline}%
}

\begin{tabular}{ | c | }
  \hline
  \printtabtoks
\end{tabular}
\end{document}
David Carlisle
  • 757,742
  • Can you explain, how does it work? – user4035 Jul 26 '16 at 07:28
  • @user4035 your code added \i three times producing a token register \i\\ \i\\ \i\\ so when you used it you got the final value of \i three times. This uses \expandafter to expand \i before adding it to the register so the register holds 1\\ 2\\ 3\\ so when you use it you get 1 2 3 – David Carlisle Jul 26 '16 at 09:13
  • Can you look here: http://tex.stackexchange.com/questions/320998/value-of-counter-from-pgffor-in-a-complex-example? I did something wrong. – user4035 Jul 26 '16 at 09:17