I was coding the other day and wrote these kinds of tests for the millionth time:
if (position("foo"; $bar) > 0)
if (find in array($bar; "foo") > 0)
if (collection has($bar; "foo"))
if ($bar{"foo"} # "")
So I said to myself, “Self, there has got to be a better and faster way to do these tests.”
In some other languages (notably python, from which I have stolen a lot of ideas), there is a keyword called in that tests for the existence of some value within a sequence of values. Looking at all of the tests above, I realized that they are all in tests.
In python, you say things like if "foo" in bar, where bar is some kind of sequence. This syntax is extremely intuitive, but unfortunately I could not use in in 4D, because in 4D an identifier can consist of multiple words separated by spaces, leading to a situation like this:
if (mylib.getValue in $myCollection)
Can you guess what goes wrong? The parser sees mylib.getValue in as a single identifier and the interpreter chokes because no such identfier exists. This can be worked around by surrounding mylib.getValue in parentheses, but that is way ugly and prone to be forgotten.
So I had to use a non-identifier character to represent in, and I chose ~. Now you can replace all of the tests above with one expression:
if ("foo" ~ $bar)
To test for not in, you use the new !~ operator. Much faster and to me more intuitive (if you see ~ as in). This operator made its appearance in v4.0rc7. I hope you take the time to use it!







