May 24, 2021 Vim
There is no doubt that the Vimscript function can accept parameters. Execute the following command:
:function DisplayName(name)
: echom "Hello! My name is:"
: echom a:name
:endfunction
Perform the following function:
:call DisplayName("Your Name")
Vim will show two lines:
Hello! My name is:
and
Your Name
Note that the parameters we pass to the
echom
command precede
a:
.
This represents the scope of a variable, as we have said in previous chapters.
Let's try what happens without a scope prefix. Execute the following command:
:function UnscopedDisplayName(name)
: echom "Hello! My name is:"
: echom name
:endfunction
:call UnscopedDisplayName("Your Name")
This time Vim complained that it couldn't find the
name
When you write a Vimscript function that requires parameters, you always need to
a:
tell Vim to go to the parameter scope lookup.
Vimscript functions can be designed to accept an indefinite number of parameters, as in Javascript and Python. Follow these commands:
:function Varg(...)
: echom a:0
: echom a:1
: echo a:000
:endfunction
:call Varg("a", "b")
This function shows us a lot of things, let's look at them one by one.
... in the function
...
E
xplains that this function can accept any number of arguments.
It's like the python function
*args
The first behavior in the function outputs the message
a:0
and the result
2
W
hen you define a function in Vim that accepts variable parameters,
a:0
set to the number of arguments you give extra . W
e just passed two parameters to
Varg
so Vim shows
2
(Translation: 2 - 0 .
The second behavior outputs
a:1
result shows
a
. Y
ou can
a:1
a:2
so on to refer to each additional argument accepted by your function.
If we use
a:2
Vim will show "b"
The third line is a bit of a puzzle. W
hen a function can accept variable parameters,
a:000
set to a list that includes all the extra parameters passed over. W
e haven't talked about the list yet, so don't get too tangled up in it.
You can't use
echom
so use
echo
here.
You can also use variable parameters with normal parameters. Execute the following command:
:function Varg2(foo, ...)
: echom a:foo
: echom a:0
: echom a:1
: echo a:000
:endfunction
:call Varg2("a", "b", "c")
We can see that
"a"
remaining "a" into the list of variable parameters as the value of the named argument
a:foo
Try the following command:
:function Assign(foo)
: let a:foo = "Nope"
: echom a:foo
:endfunction
:call Assign("test")
Vim throws an error because you cannot re-assign the argument variable. Now do the following command:
:function AssignGood(foo)
: let foo_tmp = a:foo
: let foo_tmp = "Yep"
: echom foo_tmp
:endfunction
:call AssignGood("test")
This time, Vim shows
Yep
Read
:help function-argument
Read
:help local-variables
.