I am struggling with some basic computations with Tikz and I have a problem assigning a value to a variable inside a local scope.
Consider the following MVCE:
\documentclass{article}
\usepackage{ifthen}
\usepackage{tikz}
\newcommand{\mycommand}
{
\def\myvar{0};
\def\myresult{3};
\ifnum\myvar=0
{
\def\myresult{4};
\draw (0,1) node {Test is true!};
}
\fi;
\draw (0,0) node {myresult=\myresult !!!};
}
\begin{document}
\begin{tikzpicture}
\mycommand
\end{tikzpicture}
\end{document}
Written that way, the "Test is true!" is printed, but the value of myresult stays to 3.
So I assume that the second \def command creates a new variable, whose scope is limited to the if block.
After searching a bit, it seems I can get out by defining the variable as "global", using the \global command:
\newcommand{\mycommand}
{
\def\myvar{0};
\global\def\myresult{3};
\ifnum\myvar=0
{
\global\def\myresult{4};
\draw (0,1) node {Test is true!};
}
\fi;
\draw (0,0) node {myresult=\myresult !!!};
}
That way, it works, although I am not sure this is optimal (\global seems to be a TeX command, and I've read many times that it's a bad idea to use low-level TeX commands inside a LaTeX source...)
But now, my real code is a bit more complicated, and inside the "if" bloc, its actually a \pgfmathtruncatemacro that is used.
Say something like:
\newcommand{\mycommand}
{
\def\myvar{0};
\global\def\myresult{3};
\ifnum\myvar=0
{
\pgfmathtruncatemacro{\myresult}{4}
}
\fi;
\draw (0,0) node {myresult=\myresult !!!};
}
Then I get the same problem as above: \pgfmathtruncatemacro seems to declare a new variable, as I stay with the value 3...
And both
\global\pgfmathtruncatemacro{\myresult}{4}
or
\pgfmathtruncatemacro{\global\myresult}{4}
fail to compile.
How can I get out of this problem ?


\def\myresult{4};by\xdef\myresult{4}the result is as I think you want it. (Please note also that ordinary TeX commands like\defdo not need a;in the end.) – Nov 10 '18 at 18:54\pgfmathtruncatemacro), and it still does not work (it stays with "3"). – kebs Nov 10 '18 at 18:58\globaldefs=1BUT DON'T DO THAT PLEASE. Really, why can't you use\xdef? You could just add\xdef\myresult{\myresult}after\pgfmathtruncatemacro{\myresult}{4}if you want to "broadcast" the result of a .\pgfmathtruncatemacrocomputation. – Nov 10 '18 at 19:01