[英]Vim global variable check throws error in lua (neovim plugin development)
I'm trying write a neovim plugin using lua, when checking if a variable exists, lua throws an error like: Undefined variable: g:my_var
我正在尝试使用 lua 编写一个 neovim 插件,在检查变量是否存在时,lua 会抛出如下错误: Undefined variable: g:my_var
Method 1:方法一:
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
Method 2:方法二:
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
this is a similar function written in viml
which does works: (this does not throw any error)这是用 viml 编写的类似viml
,它确实有效:(这不会引发任何错误)
fun! OpenBmaxTerm()
if exists("g:my_var")
echo "has the last buff"
else
echo "has no the last buff"
endif
endfun
any idea how to get this working in lua?知道如何让它在 lua 中工作吗? I tried wrapping the condition inside a pcall
which had an effect like making it always truthy.我尝试将条件包装在一个pcall
中,它的效果就像让它总是真实的一样。
vim.api.nvim_eval("g:my_var")
just evaluates a vimscript expression, so accessing a non-existent variable would error just like in vimscript. vim.api.nvim_eval("g:my_var")
只是评估 vimscript 表达式,因此访问不存在的变量会像在 vimscript 中一样出错。 Have you tried vim.api.nvim_eval('exists("g:my_var")')
instead?您是否尝试过vim.api.nvim_eval('exists("g:my_var")')
代替?
You can use the global g:
dictionary via vim.g
to reference your variable:您可以通过vim.g
使用全局g:
字典来引用您的变量:
if not vim.g.my_var then
print("g:my_var does not exist")
else
print("g:my_var was set to "..vim.g.my_var)
end
You can reference :h lua-vim-variables
to see other global Vim dictionaries that are available as well!您可以参考:h lua-vim-variables
查看其他可用的全球 Vim 字典!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.