不知何故,我无法执行以下映射:
function! s:MySurroundingFunctionIWantToKeep()
let s:Foobar={'foo': 'bar'}
map \42 :echo <sid>Foobar.foo<cr>
endfunction
call s:MySurroundingFunctionIWantToKeep()
我认为它的工作方式与脚本本地函数的工作方式相同:
function! s:MySurroundingFunctionIWantToKeep()
function! s:Foobar()
echo 'bar'
endfunction
map \42 :call <sid>Foobar()<cr>
endfunction
call s:MySurroundingFunctionIWantToKeep()
s:Foobar
摆脱也s:MySurroundingFunctionIWantToKeep()
无济于事,例如:
let s:Foobar={'foo': 'bar'}
map \42 :echo <sid>Foobar.foo<cr>
s:Foobar
将脚本局部变量声明为g:Foobar
全局变量就可以了。
答案1
(据我所知)没有办法直接访问该脚本上下文之外的脚本局部变量;<SID>
仅适用于函数(并且仅适用于映射)。
不过,您可以通过函数提供间接访问:
function! s:FoobarHash()
return s:Foobar
endfunction
function! s:MySurroundingFunctionIWantToKeep()
let s:Foobar={'foo': 'bar'}
map \42 :echo <sid>FoobarHash()['foo']<cr>
endfunction
call s:MySurroundingFunctionIWantToKeep()
根据您想要保持变量的隔离程度,您可以使“访问器”功能更具限制性(仅允许某些键,仅允许读取访问,仅允许写入某些键等)。
let s:Foobar={'foo': 'bar', 'baz': 'quux'}
function! s:FoobarAccess(...)
" Provide limited access to the script-local hash s:Foobar
if a:0 == 1
" allow read access to all keys
return s:Foobar[a:1]
elseif a:0 == 2
" allow write access to only 'foo'
if a:1 !=# 'foo'
throw 'FoobarAccess: not allowed to write to key ' . a:1
endif
let old = s:Foobar[a:1]
let s:Foobar[a:1] = a:2
return old
else
throw 'FoobarAccess must take exactly one or two arguments'
endif
endfunction
map \42 :echo <sid>FoobarAccess('foo')<cr>
map \43 :echo <sid>FoobarAccess('foo','new value')<cr>
map \44 :echo <sid>FoobarAccess('baz')<cr>
map \45 :echo <sid>FoobarAccess('baz',1)<cr>