我正在尝试将一些全局变量传递给 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
Run Code Online (Sandbox Code Playgroud)
所以,如果我这样做: 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>
Run Code Online (Sandbox Code Playgroud)
将此视为构建一个字符串,然后评估(/执行)它。
如需更多帮助,请参阅: :h :exe