Bma*_*max 6 lua vim-plugin neovim
我正在尝试使用 lua 编写一个 neovim 插件,当检查变量是否存在时,lua 抛出一个错误,如下所示:Undefined variable: g:my_var
方法一:
local function open_bmax_term()
if (vim.api.nvim_eval("g:my_var")) then
print('has the last buff')
else
print('has no the last buff')
end
end
Run Code Online (Sandbox Code Playgroud)
方法二:
local function open_bmax_term()
if (vim.api.nvim_get_var("my_var")) then
print('has the last buff')
else
print('has no the last buff')
end
end
Run Code Online (Sandbox Code Playgroud)
这是一个类似的函数,它viml可以工作:(这不会引发任何错误)
fun! OpenBmaxTerm()
if exists("g:my_var")
echo "has the last buff"
else
echo "has no the last buff"
endif
endfun
Run Code Online (Sandbox Code Playgroud)
知道如何让它在 lua 中工作吗?我尝试将条件包装在 a 中pcall,其效果就像使其始终为真。
小智 10
您可以使用全局g:字典 viavim.g来引用您的变量:
if vim.g.my_var == nil then
print("g:my_var does not exist")
else
print("g:my_var was set to "..vim.g.my_var)
end
Run Code Online (Sandbox Code Playgroud)
您:h lua-vim-variables也可以参考查看其他可用的全局 Vim 词典!
vim.api.nvim_eval("g:my_var")只是计算 vimscript 表达式,因此访问不存在的变量会像在 vimscript 中一样出错。你尝试过vim.api.nvim_eval('exists("g:my_var")')吗?
编辑:vim.g按照 @andrewk 建议使用可能是更好的解决方案,因为使用专用 API 比评估 vim 脚本字符串更优雅。