Skip to content

Instantly share code, notes, and snippets.

@svermeulen
Created January 29, 2015 01:54
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save svermeulen/d115ca3d5d9259dcff61 to your computer and use it in GitHub Desktop.
Clever alternative way of declaring optional parameters in vimscript
" Normal way of declaring variable arguments with default values:
function! ExampleFunc1(fix1, fix2, ...)
let var1 = a:0 > 0 ? a:1 : 'defaultVal1'
let var2 = a:0 > 1 ? a:2 : 5
echo a:fix1 .','. a:fix2 .','. var1 .','. var2
endfunction
" Alternative approach using a command:
" It will use the provided defaults if they aren't overridden by the call
function! ExampleFunc2(fix1, fix2, ...)
LetA0 var1 = 'defaultVal1'
LetA1 var2 = 5
echo a:fix1 .','. a:fix2 .','. var1 .','. var2
endfunction
function! Test()
call ExampleFunc1(5, 'foo', 'bar', 1) " 5, foo, bar, 1
call ExampleFunc1(5, 'foo', 'bar') " 5, foo, bar, 5
call ExampleFunc1(5, 'foo') " 5, foo, defaultVal1, 5
endfunction
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
command! -nargs=1 LetA0 exec <sid>DeclareParameter(0, <q-args>)
command! -nargs=1 LetA1 exec <sid>DeclareParameter(1, <q-args>)
command! -nargs=1 LetA2 exec <sid>DeclareParameter(2, <q-args>)
command! -nargs=1 LetA3 exec <sid>DeclareParameter(3, <q-args>)
command! -nargs=1 LetA4 exec <sid>DeclareParameter(4, <q-args>)
command! -nargs=1 LetA5 exec <sid>DeclareParameter(5, <q-args>)
function! s:DeclareParameter(argIndex, argStr)
let [varName, defaultValue] = split(a:argStr, '\v^\S*\zs\s*\=\s*')
return "let " . varName . " = a:0 > " . a:argIndex . " ? a:" . (a:argIndex+1) . " : " . defaultValue
endfunction
@dezza
Copy link

dezza commented Jul 6, 2016

Here's an idea for named arguments:

like: test("foo=john", "bar=halifax", "monkey=hasbanana")

if a:0
let l:iter = 1
while iter <= a:0
" split on key=value
if a:{iter} =~ "="
  let l:split_arg=split(a:{iter}, "=")
  if len(split_arg) == 2
    "echom "KEY: ".split_arg[0]." VALUE: ".split_arg[1]

    if split_arg[0] == "foo"
      let l:foo=split_arg[1]
    elseif split_arg[0] == "bar"
      let l:bar=split_arg[1]
    elseif split_arg[0] == "baz"
      let l:baz=split_arg[1]
    elseif split_arg[0] == "cmd"
      let l:cmd=split_arg[1]
    endif
  endif
else
  let l:cmd=a:{iter}
endif
let iter += 1
endwhile
endif

" argument entered
if exists("foo")
echom "FOO: ".l:foo
" global variable entered
elseif exists("g:plugin_name_foo")
echom "TARGET: ".g:plugin_name_varname
let l:foo="bar"
" default
else
echom "something else"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment