[英]Pass a function as an argument to another function in .vimrc
I have two functions in my .vimrc: 我的.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()
. 你可以做call DoStuffWrapper(DoStuff())
但它不通过DoStuff()
函数来包装,但结果DoStuff()
think about this: echo len(getline('.'))
same situation as yours. 想一想: echo len(getline('.'))
与你的情况相同。
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. 所以你想将一个函数传递给CalcFunc
,这样它就可以进行动态计算。
now if you do: 现在,如果你这样做:
call CalcFunc(2, function('SqRoot'))
it will echo 1.414214
它将回应1.414214
and if you do: 如果你这样做:
call CalcFunc(2, function('Sq'))
it will echo 4
. 它会回应4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.