Menu

#521 Function definition lacks the capability to designate a 'local' variable

None
closed-accepted
nobody
None
5
2022-10-15
2021-04-04
No

Gnuplot's evaluation process effectively passes function parameters by value. The name of a dummy parameter used to define the function is not seen by the function evaluation process:

gnuplot> f(a,b) = (a+b)
gnuplot> show at f(c,d)
        push c
        push d
        pushc 2
        calln f
          pushd1 f dummy
          pushd2  dummy
          plus

The assignment operation breaks this, however. The function is passed the name of the variable that is the target of the assignment. This name is not compared to the dummy parameter names, so the assignment ends up being made to a global variable with that name rather than to a dummy variable with that name:

gnuplot> f(a,b) = (a=b)
gnuplot> show at f(c,123)
        push c
        pushc 123
        pushc 2
        calln f
          pushc "a"
          pushc <undefined>
          pushd2  dummy
          assign

Because of this, the global variable a is overwritten every time the function f() is called, even though the user may have intended that f(c,123) has the effect c=123.

Why would you ever want to write a function that way? Consider this more complicated case:

f(x) = (tmp=expensive(x),  f1(tmp) + f2(tmp) + f3(tmp))

The user intends for f(x) to return some complicated expression whose individual terms share a common derived property of x. This works, and it does simplify the evaluation by computing the expensive derived property only once, but it has the side effect of creating or over-writing a global variable tmp. If f(x) is called from a loop, or script, etc that uses tmp for a variable name, this will clobber it.

Sometimes this global effect is intended, as in the commonly suggested mechanism for plotting some function of two successive data values:

f(y) = (ynew=func(yprev,y), yprev=y, ynew)
plot FOO using 1:(f($2))

However at other times it is not intended and the fact that calling f(x) clobbers some unrelated variable is bad. There should be a mechanism for treating tmp in the example above as a local, rather than global, variable name.

Discussion

  • Ethan Merritt

    Ethan Merritt - 2021-04-06

    Ticket moved from /p/gnuplot/bugs/2420/

    Can't be converted:

    • _milestone:
    • _priority:
     
  • Ethan Merritt

    Ethan Merritt - 2022-10-15
    • status: open --> closed-accepted
    • Group: -->
    • Priority: --> 5
     
  • Ethan Merritt

    Ethan Merritt - 2022-10-15

    Now supported in 5.5

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.