Vim Tips Wiki
Register
Advertisement
Tip 795 Printable Monobook Previous Next

created September 21, 2004 · complexity advanced · author rja · version 5.7


This tip is deprecated for the following reasons:

Vim7 added support for support for the List type for built-in arrays. See :help Lists.

It is possible to simulate arrays in Vim, without recourse to third party scripts or libraries. This can be done by dynamically constructing variable names, and then referencing their data.

For example, implementing a 1 dimensional array :

:let interests_0="Running"
:let interests_1="Swimming"
:let interests_2="Inline Skating"
:let interests_3="Cycling"
:let j = 0
:while j < 4
: let entry = 'interests_' . j
: echo entry . ':'
: echo {entry}
: let j = j + 1
:endwhile

This can be extended to 2 or more dimensional arrays :

:let interests_0_0="Walking"
:let interests_0_1="Running"
:let interests_0_2="Jogging"
:let interests_1_0="Backstroke"
:let interests_1_1="Butterfly"
:let interests_1_2="Front Crawl"
:let j = 0
:while j < 2
: let i = 0
: while i < 3
: let entry = 'interests_' . j . '_' . i
: echo entry . ':'
: echo {entry}
: let i = i + 1
: endwhile
: let j = j + 1
:endwhile

Or arrays of records :

:let academic_0_graduation_year="1995"
:let academic_0_college="Bristol Polytechnic"
:let academic_1_graduation_year="1998"
:let academic_1_college="Bristol University"
:let j = 0
:while j < 2
: let year = 'academic_' . j . '_graduation_year'
: echo {year}
: let college = 'academic_' . j . '_college'
: echo {college}
: let j = j + 1
:endwhile

References[]

Comments[]

In the same sense another possibility:

(Or to :h curly_brace_names:)

Let's assume your 12 keys are:

one
two
...
twelve

which have associated entries

1
2
...
12

To store 'em:

table_{"one"}= 1
table_{"two"}= 2
table_{"three"}= 3
...

Or if you'd prefer the opposite direction,

itable_{1}= "one"
itable_{2}= "two"
...

A loop:

let i=1
while i <= 12
echo "itable[".i."]=<".itable_{i}.">"
echo "table[".itable_{i}."]=<".table_{itable_{i}}.">"
endwhile

Example:

function! Show_table()
  let itable_{1}= "one"
  let itable_{2}= "two"
  let itable_{3}= "three"
  let itable_{4}= "four"
  let itable_{5}= "five"
  let itable_{6}= "six"
  let itable_{7}= "seven"
  let i=1
  while i <= 7
    echo "itable[".i."]=<".itable_{i}.">"
    let i=i+1
  endwhile
endfunction

Output:

itable[1]=<one>
itable[2]=<two>
itable[3]=<three>
itable[4]=<four>
itable[5]=<five>
itable[6]=<six>
itable[7]=<seven>

Advertisement