vimscript call vs. execute

风流意气都作罢 提交于 2019-12-03 05:31:07

From the experience of writing my own plugins and reading the code of others:

:call: Used to call functions:

function! s:foo(id)
    execute 'buffer' a:id
endfunction

let target_id = 1
call foo(target_id)

:execute: Used for two things:

1) Construct a string and evaluate it. This is often used to pass arguments to commands:

execute 'source' fnameescape('l:path')

2) Evaluate the return value of a function (arguably the same):

function! s:bar(id)
   return 'buffer ' . a:id
endfunction

let target_id = 1
execute s:bar(target_id)
  • :call: Call a function.
  • :exec: Executes a string as an Ex command. It has the similar meaning of eval(in javascript, python, etc)

For example:

function! Hello()
   echo "hello, world"
endfunction

call Hello()

exec "call Hello()"

Short answer

You may see call as first evaluate the expression and then discard the result. So only the side effects are useful.

Long answer

Define:

function! Foo()
    echo 'echoed'
    return 'returned'
endfunction

Call:

:call Foo()

Output:

echoed

Execute:

:execute Foo()

Output:

echoed
EXXX: Not an editor command: returned

Execute:

:silent let foo = Foo()
:echo foo

Output:

returned
Stefan109

See Switch to last-active tab in VIM

for example

:exe "tabn ".g:lasttab

Where g:lasttab is a global variable to store the current tab number and that number is concatenated with "tabnext" to switch e.g to tab number 3 (If g:lasttab e.g. contains '3' for example)

That whole string >"tabn ".g:lasttab< is evaluated and executed by VIM's exec command.

HTH?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!