Reputation: 2511
I am trying to pass some global variables to a function in a vim script. However, I end up receiving the variable names, not the actual variable values once they are passed to the function. Here is a simple case:
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
So, if I do this: nnoremap <unique> <Plug>MyHook :HookMyFunc melon apple<CR>
I get the output of: Arguments: melon apple
and when I do this: nnoremap <unique> <Plug>MyHook :HookMyFunc g:my_var_a g:my_var_b<CR>
my output is Arguments: g:my_var_a g:my_var_b
What is the way to evaluate those variables as they are passed to the function?
Upvotes: 3
Views: 2052
Reputation: 45087
You need to evaluate the line with :execute
so it will become:
nnoremap <unique> <Plug>MyHook :execute 'HookMyFunc ' . g:my_var_a . ' ' . g:my_var_b<CR>
Think of this as building up a string and then evaluating(/executing) it.
For more help see: :h :exe
Upvotes: 5