# Checking whether or not a node has been previously defined

I use the following code to draw a line to connect two nodes in my graphic:

\draw ( p-\prow-\col) -- (p-\row-\col);


At the edge of the figure, however, not every node will have a predecessor from which the line can originate.

What I would like to do is only draw the line conditionally, depending on whether the node ( p-\prow-\col) already exists or not.

I have seen this question, but the implementation and usage aren't clear to me (and it also seems to be handling the opposite case, executing when the node is undefined).

I'm simply looking for the correct syntax for the command if node is defined: do this

-

The definition of \@nodedefined in Martin Scharrer's answer to the question you linked to seems to do exactly what you ask: The command takes three arguments: The first is the node name to check, the second is the code that's executed if the node exists, and the third is the code that's executed if it doesn't exist (in this case, you'd just leave it empty).

\documentclass{article}

\usepackage{tikz}
\makeatletter
\long\def\ifnodedefined#1#2#3{%
\@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\makeatother

\begin{document}

\begin{tikzpicture}
\node (p-1-1) {P-1-1};
\node (p-2-2) at (2,2) {P-2-2};
\ifnodedefined{p-1-1}{
\draw (p-1-1) -- (p-2-2);
}{}

\ifnodedefined{p-1-2}{
\draw (p-1-2) -- (p-2-2);
}{}
\end{tikzpicture}
\end{document}

-
Thanks for your answer Jake. When I do this, I still get an error Package pgf Error: No shape named p-2-1 is known. –  nbrooks Dec 4 '12 at 19:56
Sorry, typo in the error message. I meant p-1-2, I simply ran the code from your answer. The error message comes from the draw line, so the conditional seems not to work. I'm not sure how to check the versions of TikZ or PGF...I'm using version 2.43 of TexShop as my editor, if that helps. –  nbrooks Dec 4 '12 at 20:05
There's an error there, 'at's for sure. –  Loop Space Dec 4 '12 at 20:12
Ah, ok thanks. It's version 2.10 of PGF –  nbrooks Dec 4 '12 at 20:12
@AndrewStacey Yes. Hopefully, one day I'll read what I'm writing. Thanks for the correction –  percusse Dec 4 '12 at 21:09