docwhat's avatardocwhat's blog

Vim: indirect variable access

Photo by Tuesday Temptation source

In Vim you can use a variable as a variable name.

Instead of using the variable name directly, wrap it in curly braces ({}). This will use the contents of the variable as the variable name.

let l:variable_name = 'b:infosec_username'
let {l:variable_name} = 'George'

echo exists(l:variable_name) " => 1
echo {l:variable_name} " => George

You can see how I used it my ftplugin files, such as markdown.vim on lines line 2 and line 34.

" Prevents multiple invocations
let s:guard = 'b:did_ftplugin_markdown' | if exists(s:guard) | finish | endif
" ...
" Important ftplugin code.
" ...

let {s:guard} = 1 " EOF

This makes cutting and pasting this between ftplugins much easier and less error prone.

Edit on GitHub