Created
January 29, 2015 01:54
-
-
Save svermeulen/d115ca3d5d9259dcff61 to your computer and use it in GitHub Desktop.
Clever alternative way of declaring optional parameters in vimscript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's an idea for named arguments:
like: test("foo=john", "bar=halifax", "monkey=hasbanana")