0

I just stumbled upon this strange problem:

echo 'test' ==# 0

This returns 1. Therefore it is true. But in "reality" it is not true. Any string is different from 0. How to do this check?

For a bit more context, I actually stumbled upon it with the following code:

let l= ['one', 'two', 'three']
let value = get(l, 5)
if value ==# 0
  " do something if the list does not contain index 5
else 
  " do something with the value of the 5th list item
end

get() returns 0 if the given index is not found in the list. I need to be able to check for this case. But how to do this?

0
3

By design in VimScript strings can be implicitly converted to numbers. Kind of Awk-style. Use is operator instead:

:echo 'test' is 0
0
1
  • Yes, that seems to be the solution! Thanks!
    – radlan
    Aug 3 '21 at 13:53
1

Matt has good advice for correcting your code. Here's some info on the first part of your question.

This is actually working as designed:

echo 'test' ==# 0

This compares 'test' to the number zero before displaying/echoing the result. In Vimscript when you compare a string to a number it gets converted to a number itself. Per :h variables (scroll down a bit) unless the string starts with a number it is converted to the number 0.

So the comparison reduces to this:

0 ==# 0

I.e. 1 (true) and that's what is displayed.

On the other hand, when a string starts with a number it gets converted to that number...

echo '3test' ==# 3

This also evaluates to and displays 1.

Yeah, it all may seem a little weird but Vimscript isn't the only language with automatic conversions like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.