Saucier
Saucier

Reputation: 4360

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.

Upvotes: 1

Views: 1162

Answers (1)

Kent
Kent

Reputation: 195059

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.

Upvotes: 4

Related Questions