为什么我不能将函数分配给 dict 成员作为文档状态?虚拟脚本

Why I can't assign function to dict member as documentation states? Vimscript

我正在尝试这样做

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

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

call MyFunction()

let myDict.myFunction = MyFunction
call myDict.myFunction()

来自文档:https://github.com/neovim/neovim/blob/master/runtime/doc/eval.txt#L161

输出

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

这对您来说可能是问题,也可能不是问题。

如果您不关心直接调用 myFunction(),请参阅 :help dictionary-function:help anonymous-function 以获得更简单的方法:

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

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

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