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 tried this, but it doesn't work as intended:

\foreach \x/\index in {4/0,5/1,19/2} {
  \ifnum \index > 0
     % use lastx
  \fi
  \pgfmathsetmacro\lastx{\x} 
}

How do I set \lastx properly?

share|improve this question
add comment

2 Answers

up vote 14 down vote accepted

You can use the additional facilities of foreach macro given in the manual by adding pgfmath package too. For some reason, (initially 4) option is not working if TikZ is not fully loaded so you can define it externally.

\documentclass{article}  
\usepackage{pgffor,pgfmath}
\begin{document}
\def\lastx{4}
\foreach \x[count=\xi from 2,remember=\x as \lastx] in {5,19,20,25} {
This variable \x, the value before was \lastx\space  and it is the argument \xi\space in the list.\par
}

\end{document}

enter image description here

share|improve this answer
add comment

Assignments in a \foreach are local, so you can use \xdef\lastx{\x}:

enter image description here

Code:

\documentclass{article}
\usepackage{pgffor}

\newcommand*{\lastx}{}

\begin{document}
\foreach \x/\index in {4/0,5/1,19/2} {
  \ifnum \index > 0
     % use lastx
  \fi
  \xdef\lastx{\x} 
}

Last x was \lastx
\end{document}
share|improve this answer
add comment

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.