Default value of function parameter in Vim script

From the docs, it seems that arguments can't have default values in Vim script. However, you can emulate this by defining a function with variable number of arguments, and using a:0 to determine the number of extra arguments and a:1 through a:n to access them:

function Foo(bar, ...)
  if a:0 > 0
    let xyzzy = a:1
  else
    let xyzzy = 0
  end
endfunction

You can use get to select an argument in the specific position or a default value if it's not present.

function! Foo(bar, ...)
    let baz = get(a:, 1, 0)
endfunction

Since Vim 8.1.1310 Vim also supports real optional function arguments.

However, that means that most vim installation don't support this yet. Neovim has that feature since version 0.7.0.

Example from :help optional-function-argument:

  function Something(key, value = 10)
     echo a:key .. ": " .. a:value
  endfunction
  call Something('empty')   "empfty: 10"
  call Something('key', 20) "key: 20"   

Tags:

Vim