5

I know that you can refer to script-local functions using <SID> but what about script-local variables? I tried the following, and hitting <c-space> fails:

let s:testVar = "foo"
function! s:GetTestVar()
  return s:testVar
endfunction

nnoremap <space> :echo <SID>GetTestVar()<cr>
nnoremap <c-space> :echo <SID>testVar<cr>

You can get around this by writing accessor functions (as above) but sometimes it would be nice to be able to refer directly.

Steve Vermeulen
  • 567
  • 4
  • 14
  • might be possible with the hacky method in: [vimscript - Are script local functions (s:funcName()) unit testable? - Vi and Vim Stack Exchange](https://vi.stackexchange.com/questions/17866/are-script-local-functions-sfuncname-unit-testable) – user202729 Dec 28 '22 at 14:51

2 Answers2

6

No, script-local variables are indeed private to the script. You have to write an accessor function indeed.

In plugins, this isn't so much an issue, because they should separate the functions (and with them the script's state variables) into autoload scripts, so mappings / commands (defined in the plugin script) have to refer to another script, anyway.

Ingo Karkat
  • 22,638
  • 2
  • 45
  • 58
5

I originally wanted to comment this, but I need 50 rep. Here's a small suggestion, and I hope its on target.

its possible to use (within the script where the var is defined)

exe "nnoremap <c-space> :echo ".s:testVar."<cr>"

I'm using this for s:var path insertion in mappings defined in my .vimrc. Let me know if I missed the point, or something...

dabyly
  • 51
  • 1
  • 1
  • 2
    Note that this will capture the variable's value when the line is executed rather then using the "live" value when the mapping is triggered. – Kevin Cox Oct 24 '18 at 13:24