I would like to define a function which returns the string “NaN” or sprintf(“%g”,val) depending on whether val is a string or a numeric value. Initially I was trying to test if val was defined (using the gnuplot “exists” function) but it seems that I cannot pass any undefined variable to a function (an error is issued before the function is evaluated). Therefore: is there a way to test inside a function whether the argument is a string or numeric?
I search for a function isstring which I can use somehow like
myfunc(val)=(isstring(val)?"NaN":sprintf("%g",val))
The goal is to output the values of variables without risking errors in case they are undefined. However I need it as a function if I want a compact code for many variables.
Gnuplot doesn’t really have the introspection abilities that many other languages have. In fact, it treats strings and numbers (at least integers) very similarly:
I’m not exactly sure how this is implemented internally. However, what you’re asking is very tricky to get to work.
Actually, I think your first attempt (checking if a variable exists) is more sensible as type-checking in gnuplot is impossible*. You can pass the variable name to the function as a string, but the problem is that you don’t seem to have a handle on the value. All seems lost — But wait, gnuplot has an
evalstatement which when given a string will evaluate it. This seems great! Unfortunately, it’s a statement, not a function (so it can’t be used in a function — argv!). The best solution I can come up with is to write a function which returns an expression that can be evaluated usingeval. Here goes:Now when you want to use it, you just prefix it with
evalThis goes against the grain a little bit. In most programming languages, you’d probably want to do something like this:
But alas, I can’t figure out how to make that form work.
Of course, the same thing goes here that always goes with
eval. Don’t use this function with untrusted strings.*I don’t actually know that it’s impossible, but I’ve never been able to get it to work
EDIT
In response to your comment above on the question, I think a function like this would be a little more intuitive:
With this function, your “sentinal/default” value should be
NaNinstead of"undefined", but it doesn’t seem like this should make too much of a difference…(Really, if you’re willing to live with"nan"instead of"NaN"you don’t need this function at all —sprintfwill do just fine. (Note that this works because according to IEEE,NaNdoesn’t equal anything (even itself)).