What are the possible ways to pass a variable to a function in vim? Through trial-and-error, it seems like I can do:

:call LogOutput('asdf', 'WARNING')

But not:

:call LogOutput('asdf', level='WARNING')

Is the only way to pass an argument by its index? Is there anyways to specify what that argument is for it to be more readable?

  • You could pass a dictionary, and there is a varargs thing called a:000/... – D. Ben Knoble Jun 13 '20 at 22:22
  • :h call() also. – Luc Hermitte Jun 14 '20 at 0:00

A common trick is to use a dictionary. For example,

function! DoSomething(opts) abort
    let l:opts = extend(copy(a:opts), {'foo': 42, 'bar': 0, 'baz': -1}, 'keep')

call DoSomething({'bar': 100})

But it's only good when the number of optional parameters is big. Otherwise, it's simpler just to stick to positional arguments:

function! DoAnotherThing(...) abort
    let l:foo = get(a:, 1, 42)
    let l:bar = get(a:, 2)
    let l:baz = get(a:, 3, -1)

call DoAnotherThing(42, 100)

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.