Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of function parameter in Vim script

Tags:

vim

How to specify default value (e.g. 0, None) for a parameter in Vim script?

like image 478
Vayn Avatar asked May 26 '11 07:05

Vayn


People also ask

What is default function parameter?

Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

What is default parameter in es6?

Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.


3 Answers

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 
like image 70
hammar Avatar answered Oct 14 '22 16:10

hammar


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
like image 37
theJian Avatar answered Oct 14 '22 16:10

theJian


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"   
like image 28
radlan Avatar answered Oct 14 '22 14:10

radlan