Generic vim counters

I needed a way in vim config to use counters and what better way, but to write a function to simultaneously handle all variables and optinally increase or decrease them:

" define and manage counters
" NB! all counters are namespaced globally (g:)
function! Counter(name,...)
" check if this variable already exists or should we initialise it
  if !exists("g:" . a:name)
    exec 'let g:'  . a:name .' = 0'
  endif
" if second parameter is given, increase/decrease value
  if a:0 > 0
    exec 'let g:'. a:name .' = g:' . a:name . ' + ' . a:1
  endif
  exec 'return g:' . a:name
endfunction

Usage of the function is as follows:

" Get the current value
echo Counter('mycount')

" Increase value by 1(and return the new value)
echo Counter('mycount', 1)

" Decrease value by 2
echo Counter('mycount', -2)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s