I'm having a hard time understanding why the following equivalence produces two different results:

echom a:events == '*' 
echom string(a:events) == '*'

The first one returns 1 while the second one returns 0. Why is this so?

  • what is a:events? – Mass Jun 28 at 1:17

In vim, string() does not mean cast or convert a value to a string. It means create a new string which can be eval'd back the original value:

eval(string(x)) ==# x

So assuming a:events is a sting with the literal value *, then string(a:events) is the literal value '*'. The string had 1 character, but now has 3 characters.

As another example,

echo 'hello'->string()->string()->string()



Casting strings in vim script

Explicitly casting to a string is not always needed (as opposed to some other languages) since numbers are automatically converted to/from strings when necessary. For example,

strlen(123) = 3

Although vim script does have a distinct number and string type, you generally don't need to keep track of it yourself. But if you do need it, there's are a couple of options:

1: Since the only issue with string() is when the type is already string, we can just check first.

let x = type(x) == v:t_string ? x : string(x)

2: Per the documentation %s performs the conversion to string like :echo

printf('%s', x)
| improve this answer | |
  • what would be the closest thing to 'cast to string' in vimscript? Or does that not really exist? – David542 Jun 28 at 1:31
  • using string() carefully :) please see my edit. – Mass Jun 28 at 1:48

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.