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

How to pass variables as arguments of a function in a vim script

我正在尝试将一些全局变量传递给 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

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

您需要计算带有 :execute 的行,因此它将变为:

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

将此视为构建一个字符串,然后对其求值(/执行)。

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