How to specify default value (e.g. 0, None) for a parameter in Vim script?
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With