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.

  • I added code to my answer for coping with your problem and also the one in your other question – egreg Jul 26 '16 at 9:47
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}
  • Can you explain, how does it work? – user4035 Jul 26 '16 at 7: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 9:13
  • Can you look here: tex.stackexchange.com/questions/320998/…? I did something wrong. – user4035 Jul 26 '16 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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