question

Mischa Spelt avatar image
2 Likes"
Mischa Spelt asked Mischa Spelt commented

Strings arithmetic with a Variant

@Patrick Zweekhorst found some interesting behavior when variants containing strings are involved in arithmetic. For example, consider the following:

Variant str = "Hello world";
return [1 + str, str + 1, 60 * str, str * 60, str / 10, 10 / str];
// Gives [1, 1, 0, 60, 10, 1.#INF00]

I cannot even figure out what is going on here: sometimes strings behave as the identity (0 for addition, 1 for multiplication) but not always and the operators no longer even seem commutative.

It would have made sense if this threw an exception, or even just gave 0.

Of course, the solution is not to use strings and check the type first before you do. But in this case, where the variant was read from a table (str = Table("GlobalTable")[1][1]) it took a while to figure out what went wrong in the model, since the resulting numbers (aside from 10 / str) look quite reasonable.

Choose One
variantstrings
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

·
Jordan Johnson avatar image
4 Likes"
Jordan Johnson answered Mischa Spelt commented

In all the examples you have given, you are using a binary operator with a Variant and a non-variant (int or double) value. If the Variant is on the right, then the variant is first cast to a number. in the case of the string variant, that will always be zero. If the Variant is on the left, the Variant checks to see if it is a number type. If it is, it casts itself to a number and does the operation. If not, the operator will return the value on the right.

If both values are Variants, then both must be string or number types. In the string case, you can only add. If you are not adding strings, or if the types mismatch, you will get a null value.

This behavior is by design. @anthony.johnson may have some further insight. As a way to catch this issue sooner, try to do Variant math rather than Variant/non-Variant math. This will produce null values, rather than numbers, if there is a type mismatch.

· 1
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Mischa Spelt avatar image Mischa Spelt commented ·

Thanks for the explanation Jordan. I guess what made the least sense to me was
"If not, the operator will return the value on the right."

0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.