small medium large xlarge

Mark1_pragsmall
27 Mar 2015, 00:20
R. Mark Volkmann (13 posts)

About page 3 in version 1.1 of the book, do I have this right? “a” is a List of all arguments. “a:000” is a List of only the optional arguments that follow the required arguments.

5_pragsmall
27 Apr 2015, 19:37
Benjamin Klein (7 posts)

Close. a: is the prefix for the argument scope, so in a function with required (or named) arguments, we use it to access those:

function! ForInstance(foo)
  echomsg 'foo is ' . a:foo
endfunction

Vim also gives optional arguments a number (rather like a name), in the order that they’re given:

function! ForInstance(foo, ...)
  echomsg 'foo is ' . a:foo . ', and the first optional argument is ''' . a:1 . ''''
endfunction

:call ForInstance(42, 'Hi!', 'Yo!)

will return

foo is 42, and the first optional argument is 'Hi!'

a:000 is a List, and it is an alternate way to get at those optional arguments.

function! ForInstance(foo, ...)
  echomsg 'foo is ' . a:foo . ', and the first optional argument is ''' . a:1 . ''''
  echomsg 'Also, the first item in a:000 is ''' . a:000[0] . ''''
endfunction

:call ForInstance(42, 'Hi!', 'Yo!)

gives us

foo is 42, and the first optional argument is 'Hi!'
Also, the first item in a:000 is 'Hi!'

The actual type of each optional argument depends on what we pass in. (VimL’s type() function returns a number from 0–5 for the type of a given variable; 1 is a String and 5 is a Float.

function! ForInstanceAgain(foo, ...)
  echomsg 'The first optional argument, a:1, is of type ' . type(a:1)
  echomsg 'The second optional argument, a:000[1], is of type ' . type(a:000[1])
endfunction

:call ForInstanceAgain(42, 'Hi!', 0.1)

and we get

The first optional argument, a:1, is of type 1
The second optional argument, a:000[1], is of type 5
You must be logged in to comment