[Tex/LaTex] Tikz coordinate calculations inside foreach

calculationscoordinatesforeachtikz-pgf

As part of a drawing that will go with an explanation of diffraction, I want to draw the "outer rays" of a beam of light and draw several rays in between. An MWE of how I'm going about this is shown below:

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}[scale=1]
    \draw[black,semithick] (-3,1) -- (0,1);
    \draw[black,semithick] (-3,-1) -- (0,-1);
    \def \n {10}
    \foreach \s in {1,...\n-1}
    {
        \draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
    }
\end{tikzpicture}
\end{document}

This gives me the following error:

Runaway argument?
\pgffor@stop \pgffor@@stop \expandafter \pgffor@dots@charcheck \pgffor@dotsvalue \ETC.
! File ended while scanning use of \pgffor@dots@stripcontext.

The pgffor@dots stuff makes me suspect the problem might lie in the range specification for \s but as far as I can tell there's nothing wrong with it. Can anyone enlighten me?

Best Answer

You are missing , in {1,...\n-1} which should be {1,...,\n-1} Note the , after .... Further I have defined \n-1 as a macro and taken it outside the loop (this can be done with the facilities of \foreach too though).

\documentclass{standalone}
\usepackage{pgfplots,tikz}
\usetikzlibrary{calc}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}[scale=1]
    \draw[black,semithick] (-3,1) -- (0,1);
    \draw[black,semithick] (-3,-1) -- (0,-1);
    \def \n {10}
    \pgfmathsetmacro{\tmp}{\n-1}
    \foreach \s in {1,...,\tmp}
    {
        \draw[lightgray,semithick] ($(-3,1)!\s/\n!(-3,-1)$) -- ($(0,1)!\s/\n!(0,-1)$);
    }
\end{tikzpicture}
\end{document}

enter image description here