1

Supposing I have two scripts that share variables. What is the preferred way to do this, supposing I wanted to keep the variables only in one place? Is there a way to keep them script-local and not global?


Context: I'm writing two syntastic syntax checkers that both the same errorformat (because underneath they use the same compiler). What would be the preferred way to share an errorformat variable between the two files of these syntax checkers?

I was later explained by the maintainer that since these variables aren't meant to be changed often, I should just have them in two places. This question is still here because the how-to question is still answerable, although it is no longer relevant in the original context.

  • The preferred way would be to leave the two copies alone. The errorformat shouldn't change more often than once in a few years, so who cares. Trying to make it "shared" creates a problem instead of solving one. If you use a global variable, you need to make sure it's initialised before either checker gets to run. If you use a common include you're writing more code than you're avoiding. – lcd047 May 17 '16 at 14:29
  • It's a misleading question. The solution for your particular setup is not the solution that should be used "in general". – lcd047 May 17 '16 at 14:33
  • @lcd047 you are quite right, I rewrote the question to separate the actual question and the context. – user2598 May 17 '16 at 14:38
2

You should use a global variable:

:h global-variable

                    *global-variable* *g:var* *g:*
Inside functions global variables are accessed with "g:".  Omitting this will
access a variable local to a function.  But "g:" can also be used in any other
place if you like.

You can use it as follow:

let g:my_variable = 1

And then g:my_variable is accessible from anywhere within vim and plugins.

  • So there is no way to limit the scope to those files that need it? – user2598 May 17 '16 at 11:01
  • 1
    mh not that I can think of, but you should see :h internal-variables to see all options for variable scoping. – nobe4 May 17 '16 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy