为什么我能';是否将功能分配给dict成员作为文档状态?Vimscript

为什么我能';是否将功能分配给dict成员作为文档状态?Vimscript,vim,Vim,我正试着这么做 let myDict = { 'lang': 'vimscript' } func! MyFunction() echo "self exists => " . exists("self") endfun call MyFunction() let myDict.myFunction = MyFunction call myDict.myFunction() 从文档中: 输出 self exists => 0

我正试着这么做

let myDict = { 'lang': 'vimscript' }

func! MyFunction()
  echo "self exists => " . exists("self")
endfun

call MyFunction()

let myDict.myFunction = MyFunction
call myDict.myFunction()
从文档中:

输出

self exists => 0                                                                                                                                                                                           
Error detected while processing /Users/gecko/.vim/plugged/vim-ansible-execute-task/foo.vim:
line    9:
E121: Undefined variable: MyFunction
E15: Invalid expression: MyFunction
line   10:
E716: Key not present in Dictionary: myFunc

要么该示例完全错误,要么它默认假定
MyFunction
是一个funcref。在这两种情况下,信息都是错误的,因此您可能应该打开一个问题

您应该分配一个
:help funcref
,而不是函数本身:

let myDict = { 'lang': 'vimscript' }

function! MyFunction()
  echo "self exists => " . exists("self")
endfunction

call myFunction()
" self exists => 0

let myDict.myFunction = function("MyFunction")
call myDict.myFunction()
" self exists => 0
请注意,在这种情况下,函数不会获得
self
。如果您想要
self
,则必须添加
dict
属性,但这将导致无法直接调用
myFunction()

let myDict = { 'lang': 'vimscript' }

function! MyFunction() dict
  echo "self exists => " . exists("self")
endfunction

call myFunction()
" E725

let myDict.myFunction = function("MyFunction")
call myDict.myFunction()
" self exists => 1
let myDict = { 'lang': 'vimscript' }

function! myDict.myFunction()
  echo "self exists => " . exists("self")
endfunction

call myDict.myFunction()
" self exists => 1
这对你来说可能是个问题,也可能不是

如果您不想直接调用
myFunction()
,请参阅
:帮助字典函数
:帮助匿名函数
,了解更简单的方法:

let myDict = { 'lang': 'vimscript' }

function! MyFunction() dict
  echo "self exists => " . exists("self")
endfunction

call myFunction()
" E725

let myDict.myFunction = function("MyFunction")
call myDict.myFunction()
" self exists => 1
let myDict = { 'lang': 'vimscript' }

function! myDict.myFunction()
  echo "self exists => " . exists("self")
endfunction

call myDict.myFunction()
" self exists => 1