3

What are the truthy and falsey values in classic vimscript (not vim9script)?

What is the canonical list, and where do I find it in :help?

3

TL;DR:

Truthy:

  • Non-0 Numbers (any integer but 0)
  • Strings that convert to a non-zero number
    • All strings starting with a digit which is not '0'
    • Numbers not starting with '0', eg: -123 0x10 0177 0o177 0b1011

Falsey:

  • 0 in integer form only -- float 0.0 gives E805: Using a Float as a Number
  • v:false, v:none and v:null
  • Any string that evaluates as 0 when 0 is added to it, eg: 'foo', '0.9'(!) and even '+1'(!!!)

Error:


:help Boolean says:

For boolean operators Numbers are used. Zero is FALSE, non-zero is TRUE. You can also use v:false and v:true.

Note the emphasis on Numbers. Strings can be converted to Numbers. Floats can't.

But that's not the complete story on the false side.

Neovim doesn't have a help index for Specials, but vim's :help Specials says:

v:false, v:true, v:none and v:null.

These were introduced in Patch 7.4.1154.

Reading the help on these, we find that when used as Numbers, they respectively evaluate to:

      0,       1,      0,   and    0

To test if a string is truthy or not, add the Number 0 to it, eg:

:if '-1' + 0 | echo "true" | else | echo "false" | endif

The following strings all convert to the number 0 and are thus false:

  • '0'
  • '0.9'
  • ''
  • 'non-number'
  • '+1' (!!!)

Note especially last one:

  • '-1' converts to -1 (truthy)
  • '+1' converts to 0 (falsey)

Any string starting with a digit that is not 0 is true. '0.9' is false

:help Boolean says:

If the string starts with a non-zero number it means TRUE

But note the following:

  • Truthy: '0xff' and '0777' (Non-0 integers)
  • Falsey: 0.9 (Float converts to integer 0)
2
  • Great reference. v:true is relatively new, so many plugins still use 0/1, and the docs often say things in terms of 0/1. New code really should use v:true/v:false unless it absolutely needs the type-punning here
    – D. Ben Knoble
    Dec 22 '21 at 16:48
  • 2
    This actually gets even more confusing... Because Vim also uses a different concept of "truthy" and "falsy" (which it actually calls by these names) that is only used for the ?? operator. See :help truthy and :help ??.
    – filbranden
    Dec 22 '21 at 19:08

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.