Assigning a numerical variable with Tikz pgfmathtruncatemacro

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}
{
    defmyvar{0};
    defmyresult{3};
    ifnummyvar=0
    {
        defmyresult{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}
{
    defmyvar{0};
    globaldefmyresult{3};
    ifnummyvar=0
    {
        globaldefmyresult{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}
{
    defmyvar{0};
    globaldefmyresult{3};
    ifnummyvar=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

globalpgfmathtruncatemacro{myresult}{4}

or

pgfmathtruncatemacro{globalmyresult}{4}

fail to compile.

How can I get out of this problem ?

Leave a Reply

Your email address will not be published. Required fields are marked *