4

What is the proper way to check if a particular variable is null? I use v:null as a special value to indicate something in a custom function's return value.

I have tried:

let l:v = v:null
echom l:v == v:null   " Works fine
let l:v = {'file': "something"}
echom l:v == v:null   " E735: Can only compare Dictionary with Dictionary

Note for searchers: null is sometimes called None, empty or nil.

4
  • 1
    I would try is instead of == (can't test rn).
    – Biggybi
    Dec 16, 2021 at 11:19
  • Correct, thank you. It would be great to specify in the answer also how to test 'is not' - it is a bit counterintuitive echom !(l:v is v:null) Dec 16, 2021 at 11:25
  • 1
    Actually, there's also isnot. I'm writing an answer.
    – Biggybi
    Dec 16, 2021 at 11:47
  • 1
    I almost always write is# even when it's not needed, and almost never write ==. Then I have less thinking to do, and I don't get weird conversions I don't want (strings and numbers). This is likely because Martin persuaded me with the article linked in the answer.
    – D. Ben Knoble
    Dec 16, 2021 at 16:32

1 Answer 1

2

The == operator will check for value.

You need to check identity. This is done with the is (and isnot) operator. Use is# to match the case, is? to ignore it.

For example:

if l:v is v:null
  echom "Null"
endif
if l:v isnot v:null
  echom "Not null"
endif

There is a list of operators at :h expr4. You can use e.g :h expr-== as well, or just :h ==.

I also recommend reading Effective VimScript from Martin Tournoij.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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