2

If I define the variable foo like this:

:let foo = '~/Desktop'

And I want to check the length of the string it contains, then I can type:

:echo strlen(foo)

The output is 9, which is right.
If I had typed :echo strlen('foo'), the output would have been 3, because Vim would have calculated the length of the string 'foo' instead of the evaluation of the variable foo.

Next, I want to expand the filepath contained in foo.
The following command doesn't echo any message:

:echo glob('foo')

But the following does output something (/home/username/Desktop):

:echo glob(foo)

So, these 2 examples seem to show that if I want to pass the evaluation of a variable name as an argument to a function, I must not put quotes around it.

Now, if I want to check whether the variable foo exists and has been defined, and I type:

:if exists(foo) | echo "success!" | endif

There's no output. However, the following works:

:if exists('foo') | echo "success!" | endif

This time, it was different, as I needed to put quotes around foo for it to be evaluated by exists(). Why do I need to use quotes with exists() but neither with strlen() nor with glob() ?

When do you need to put quotes around a variable name which is passed as an argument to a function?

4

It has to do with the nature of exists():

Note that the argument must be a string, not the name of the
 variable itself.  For example: 
         exists(bufcount)
This doesn't check for existence of the "bufcount" variable,
 but gets the value of "bufcount", and checks if that exists.

Since exists() examines the contents of the argument, if you want to check if a variable named foo exists, you must pass it a string containing foo. You could have done the following just as well (after defining foo):

:let bar = 'foo'
:if exists(bar) | echo "success!" | endif

So, you need to quote the variable and make it a string, when you're interested in dealing with the variable itself, not its contents.

  • 1
    Ok, so when I said that exists() did not evaluate the variable, I was wrong. exists() is no different than strlen(), glob() or any other function. No matter the function, Vim always evaluates the variable before sending the result to the function. Usually this is what you want. But not with exists(), because usually you don't want to check whether the contents of a variable exists but whether the variable itself exists. So, the quotes are here to tell Vim: "don't evaluate the variable, leave it as it is". – saginaw Dec 24 '15 at 5:40

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.