简体   繁体   中英

Pass a function as an argument to another function in .vimrc

I have two functions in my .vimrc:

function! DoStuff()
    ...
endfunction

function! DoStuffWrapper(func)
    ...
    func
    ...
endfunction

nnoremap <Leader> ...

Basically that works. But I'm not sure if it is the right thing to do. Are there better alternatives to pass a function inside another function?

I saw approaches like

function! AFunction()
    ...
    :call call (function('FunctionName'), params)
    ...
endfunction

but that does only seem to work while using the functions name and not an argument.

You can do call DoStuffWrapper(DoStuff()) however it does not pass DoStuff() function to the wrapper, but the result of DoStuff() . think about this: echo len(getline('.')) same situation as yours.

I hope this example could explain a little bit for you:

fun! Sq(val)
    return a:val*a:val
endf


fun! SqRoot(val)
    return sqrt(a:val)
endf

fun! CalcFunc(val, func)
    echo a:func(a:val)
endf

so you want to pass a function to the CalcFunc , so that it could do dynamic calculation.

now if you do:

call CalcFunc(2, function('SqRoot'))

it will echo 1.414214

and if you do:

call CalcFunc(2, function('Sq'))

it will echo 4 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM