Change global tikz style from inside a tikz pic

OK, guys. I had a strange idea and wanted to check with you if there is a way to do it. I couldn't get any insight from the pgfmanual, and I couldn't find similar questions either.

I wanted to use a tikz pic to create dynamic tikz pics. It would work as a "savebox" but calculated in "real time", if I could say so. Let me show you my code:

\documentclass{standalone}

\usepackage{tikz}

\tikzset{
pics/meta/.style 2 args={
code={
\tikzset{
#1/.pic={
\node[fill=#2]{};
}
}
\pic{#1};
}
}
}

\begin{document}
\begin{tikzpicture}
\pic[]at(0,0){meta={r}{red}};
\pic[]at(1,0){meta={g}{green}};

\pic[]at(2,0){r};
\pic[]at(3,0){g};
\end{tikzpicture}
\end{document}


This code "almost" works. The pic inside of the meta draws correctly, but the outside pics give me an error like "I do not know the key /tikz/pic/r".

I assume that this is a scope problem, since the "r" key disappear after leaving the "meta" definition. Hence my question: is there a way to add a key to the global scope from inside of a local group? For regular LaTeX, we have macros like \gdef and \xdef.

Edit:

It is very easy to workaround this by using a regular macro instead of a tikz pic to create the dynamic style. Anyway, let's keep this as a challenge (if it is).

Yes, that can be done. With @percusse's answer you can globalize pgf keys.

\documentclass{standalone}

\usepackage{tikz}

\tikzset{
pics/meta/.style 2 args={
code={\begingroup\globaldefs=1\relax
\tikzset{
#1/.pic={
\node[fill=#2]{};
}
}
\endgroup
\pic{#1};
}
}
}

\begin{document}
\begin{tikzpicture}
\pic[]at(0,0){meta={r}{red}};
\pic[]at(1,0){meta={g}{green}};

\pic[]at(2,0){r};
\pic[]at(3,0){g};
\end{tikzpicture}
\end{document}