Re: Passing zero as a Parameter/ NOT KEYWORD_SET [message #16066 is a reply to message #16065] |
Tue, 29 June 1999 00:00   |
J.D. Smith
Messages: 214 Registered: August 1996
|
Senior Member |
|
|
Martin Schultz wrote:
>
> J.D. Smith wrote:
>>
>>
>> That's a bit dangerous. [...]
> Indeed ;-)
>>
>> The best way to proceed is pretend keyword_set() was really
>> named is_defined_and_non_zero(). Forget that it's called
>> keyword_set().
> In fact it is "is_defined_and_uneven" !
> Just try to pass var=2 into a routine and print keyword_set(var). Hope,
> David will take notice of this in his article.
I get 1 printed if var is anything but zero or undefined. This sounds
like a bug on your version/system, if it's really occurring. So I'll
stick with is_defined_and_non_zero(): a bit of a mouthful, but much less
misleading.
> Another marginal point about setting default values: I recently learned
> from someone's code (cannot remember whose), to use
> if (n_elements(var) ne 1) then var=default
> instead of
> if (n_elements(var) eq 0) then var=default
>
> The advantage being that you can prevent program crashes when someone
> passes a vector or array in what is supposed to be a scalar.
>
Unless, of course, you *are* interested in a vector or array. You're
mixing two types of checks here: "is the argument there at all?", vs.
"is the argument of the type I want?"... (n_elements(var) eq 0) will
work for any type of expected variable; (n_elements(var) ne 1) only
works if you expect a scalar. You are of course free to do this type of
mixing where appropriate (though you don't have to), but for the benefit
of those just learning, I thought I should try to make this clear.
> And, finally: Use keyword_set when you want to make sure the value of a
> boolean flag is defined:
> flag = keyword_set(flag)
> Then, later in the code, it's just
> if (flag) then ...
> Or value = x+y*(flag), etc. which would crash otherwise.
Yes, another good use of keyword _set().
JD
--
J.D. Smith |*| WORK: (607) 255-5842
Cornell University Dept. of Astronomy |*| (607) 255-6263
304 Space Sciences Bldg. |*| FAX: (607) 255-5875
Ithaca, NY 14853 |*|
|
|
|