Vimscript: Lists (arrays) and loops

The square bracket syntax denotes a list: let thing = ['one', 'two', 'three'].

For loops begin with for and end with endfor. And use the in keyword to loop over a list:

function Hi()
  let things = ['one', 'two', 'three']
  for thing in things
    echo thing
  endfor
endfunction

:call Hi() will print the items in the list, one at time, at the prompt.

You can concatenate lists with + and a new array. You can use this as a makeshift add operator, too.

function Hi()
  let things = ['one', 'two', 'three']
  let new_things
  for thing in things
    let new_things = new_things + ['new'.thing]
  endfor
  echo new_things
endfunction

(The . operator concatenates strings)

:call Hi() will now print ['newone', 'newtwo', 'newthree'].

vimscript

Edit on github
comments powered by Disqus
Click me