4

In h: internal-variables it mentions the "global" variable which is prefixed by g:. What would be the difference between:

let g:var = "xyz"

And:

let var = "xyz"

Does the absence of a prefix mean g:, or are they two different things?

1
  • Depends on context: the scope default to different things depending on where its used (script local in scripts, function local in functions, i think. Plus there are buffer and window local, which are never defaults)
    – D. Ben Knoble
    Jun 13, 2020 at 3:41

1 Answer 1

16

In VimScript all variables have a scope. Or, better to say, they are organized into :h Dictionaries with reserved names. So echo g: is a perfectly valid command.

There are the following scopes (dictionaries) in no particular order:

  1. g: Global
  2. s: Script-local (like "static" in C)
  3. l: Function-local
  4. a: Function argument
  5. v: Vim internal
  6. b: Buffer local
  7. w: Window local
  8. t: Tab local

If scope is not given then v: is searched. If there's no such variable in v: then it's either s: or l: depending on the execution context. Also, while on the command line it's g:, as, obviously, neither s: nor l: applies in interactive mode.

5
  • thanks, so if I execute :let var = "new" then that goes into the g: dict because I haven't qualified its prefix/namespace?
    – David542
    Jun 13, 2020 at 6:40
  • 1
    Interactively? Yes. You can always check it with echo g:var or echo get(g:, 'var')
    – Matt
    Jun 13, 2020 at 6:43
  • 1
    I did not know for nothing that could be interpreted as s:... oO BTW, there is also a little issue with lambdas: we have to be explicit to use global variables, even interactively, while it's not the case in echo map(somelist, 'v:val > globalthreshold'). Jun 13, 2020 at 13:29
  • @LucHermitte Lambda is a kind of closure, so it's normal when it inherits default meaning of l:, a: and s: as if executing in the outer scope. However, it's really strange that "global" lambda does not have g: by default. Should it be called inconsistency or bug?
    – Matt
    Jun 13, 2020 at 14:20
  • @Matt, I'd say inconsistency. Jun 13, 2020 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.