[Tex/LaTex] what is the correct syntax for using let in tikz picture

tikz-pgf

I am looking at this answer But still can't get the syntax right.

I have this example to draw a line of length 2 units, which works fine:

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,calc,decorations.markings}
\begin{document}
\begin{tikzpicture}
\draw  (0,0) -- ({2*cos(30)},{2*sin(30)});
\end{tikzpicture}
\end{document}

I want to make the length a variable. So I wrote (following the answer in the link above)

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,calc,decorations.markings}
\begin{tikzpicture}
\draw let \r1={2} in 
        (0,0) -- ({\r1*cos(30)},{\r1*sin(30)});
\end{tikzpicture}
\end{document}

But this gives syntax error

    Package tikz Error: ``\p'' or ``\n'' expected. \draw let \r

I thought maybe the { is confusing it. So I changed it to

\begin{tikzpicture}
\draw let \r1={2} in (0,0) -- (\r1*{cos(30)},\r1*{sin(30)});
\end{tikzpicture}

Still an error. I kept trying different things, and they all are failing. So I gave up. I know I need to have {} in tickz when doing calculations. So I do not understand the problem.

Any help on the correct syntax?

Update

I also tried p1 but it gives this error

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,calc,decorations.markings}

\begin{tikzpicture}
\draw let \p1={2} in (0,0) -- ({\p1*cos(30)},{\p1*sin(30)});
\end{tikzpicture}
\end{document}

 Extra }, or forgotten \endgroup. \draw let \p1={2}

Then I tried removing the {}

 \draw let \p1={2} in (0,0) -- (\p1*cos(30),\p1*sin(30));

An error. I tried keeping the {} around the trig only

  \draw let \p1={2} in (0,0) -- (\p1*{cos(30)},\p1*{sin(30)});

error. I also tried

   \draw let \p1={2} in (0,0) -- ({\p1}*{cos(30)},{\p1}*{sin(30)});

error.

Tikz syntax is mystery to me.

Best Answer

2 is a number, thus the let assignment would be \n1 or \n{r1} if the variable is named 1 or r1. \p expects a point, e.g., \p{1} = (3, 4). \x1 and \y1 then selects the x and y components of point \p1. \r is not defined.

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,calc,decorations.markings}

\begin{document}
\begin{tikzpicture}
\draw let \n1={2} in
        (0,0) -- ({\n1*cos(30)},{\n1*sin(30)});
\end{tikzpicture}
\end{document}

With the new math library, \r1 can be defined as array variable \r:

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{arrows,calc,decorations.markings,math}

\begin{document}
\begin{tikzpicture}
\draw[evaluate={
  \r1=2;
}]
  (0,0) -- ({\r1*cos(30)},{\r1*sin(30)});
\end{tikzpicture}
\end{document}