0

As I know, both of them can do quite the same things, but one should call to invoke and other one should use execute to invoke.

But whats the difference between command and function? when should I use one and other?

1
  • 1
    Clarification: you don’t always need call for a function (automatic when an expression is expected) and you don’t always need execute for a command (only when doing string interpolation). – D. Ben Knoble May 29 at 13:17
2

Think it as "shell scripting": "Command" is a word that stands at the start of command-line. What follows a command is either "string parameter(s)" or "expression(s)" (that is essentially "evaluate-able" string parameter). Commands never return anything and hence they cannot be evaluated (except something like :h execute() but it really counts as "redirection", not as "evaluation").

"Function" in VimScript is simply a special sort of "expression". Therefore no function may take place at command-line start. All functions return a value and so, unlike commands, they may stand on the RHS of assignment.

So it follows that one is able to invoke commands directly: :SomeCommand some args; but calling a function requires starting from some command able to evaluate expression(s), e.g. :call MyFunction(1, 2, 3).

So, apart from syntactical differences, you can use them interchangeably, but from practical point of view commands are easier to type for an end-user, while creating a long command implies all those complicated rules about command line continuation, command separation, command line specials expansion and so on. Also, functions provide local variables and auto-loading features. So typical solution is to create a command that calls internal implementation function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.