如何在vim脚本中将变量作为函数的参数传递

时间:2015-04-15 22:31:12

标签: vim macvim

我正在尝试将一些全局变量传递给vim脚本中的函数。但是,一旦传递给函数,我最终会收到变量名,而不是实际的变量值。这是一个简单的案例:

let g:my_var_a = "melon"
let g:my_var_b = "apple"

" Define the main function
function! MyFunc(myarg1, myarg2)
    echom "Arguments: " . a:myarg1 . ", " . a:myarg2
endfunction

" Link the function to a command
command! -nargs=* HookMyFunc call MyFunc(<f-args>)

" Link the command to a plug
nnoremap <unique> <Plug>MyHook :HookMyFunc g:my_var_a g:my_var_b<CR>

" Assign a key to the plug
nmap <silent> <leader>z <Plug>MyHook

所以,如果我这样做:nnoremap <unique> <Plug>MyHook :HookMyFunc melon apple<CR>

我得到了输出:Arguments: melon apple

当我这样做时:nnoremap <unique> <Plug>MyHook :HookMyFunc g:my_var_a g:my_var_b<CR>

我的输出是Arguments: g:my_var_a g:my_var_b

在将这些变量传递给函数时评估这些变量的方法是什么?

1 个答案:

答案 0 :(得分:4)

您需要使用:execute评估该行,以便它变为:

nnoremap <unique> <Plug>MyHook :execute 'HookMyFunc ' . g:my_var_a . ' ' . g:my_var_b<CR>

将此视为构建字符串然后评估(/执行)它。

如需更多帮助,请参阅::h :exe

相关问题