3

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?

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.