VimL/Vimscript: 如何从内部函数访问外部函数的局部变量?

VimL/Vimscript: how to access local variable of outer function from its inner function?

我有以下形式的函数:

function! s:my_function(dict_arg)
    let darg = copy(a:dict_arg)

    func! my_inner_func(cond)
        if a:cond ==# 'a'
            execute darg.a
        elseif a:cond ==# 'b'
            execute darg.b
        elseif a:cond ==# 'c'
            execute darg.c
        endif
    endfunc

    return function('my_inner_func')
endfunc

其中传递给 dict_arg 参数的参数将是一些用 abc 键入的字典,它们各自的值是表示 Ex 命令的字符串将根据特定的 cond(条件)执行。

外部函数s:my_function的目的是生成一个Funcref,它将根据cond,它本身由其他变量在别处决定。

所以我的问题是我不知道如何从my_inner_func中引用s:my_function范围内定义的局部变量darg 当函数被调用时,我得到错误 E121: Undefined variable: darg。如果我不定义局部变量 darg,它也不起作用(同样的错误),而只是尝试做 execute a:dict_arg.b 例如。

我可以通过将 darg 定义为全局的来绕过它,如在 let g:darg = copy(a:dict_arg) 中,然后再定义 execute g:darg.a。但当然,我想避免这种情况。

在类似 Python 的情况下,这种类型的词法范围解析是自动的。但是 VimL 很好.. VimL。任何帮助或指点将不胜感激。

In something like Python, this type of lexical scope resolution is automatic

在 VimScript 中,除了 lambda 表达式,它是手动。您必须明确添加 closure 关键字:

func! my_inner_func(cond) closure
    ...
endfunction

The purpose of the outer function s:my_function is to generate a Funcref that will execute the appropriate Ex command (darg.a, darg.b or darg.c) based on the cond, which is itself determined elsewhere by other variables.

IMO,最好使用"a partial"。

function! InnerFunc(foo, bar, baz)
    ...
endfunction
...
let OuterFunc = function('InnerFunc', ["FOO", "BAR"])
call OuterFunc("BAZ")