6

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

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)

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? I tried wrapping the condition inside a pcall which had an effect like making it always truthy.

Bmax
  • 590
  • 4
  • 11
  • 24

2 Answers2

9

You can use the global g: dictionary via vim.g to reference your variable:

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

You can reference :h lua-vim-variables to see other global Vim dictionaries that are available as well!

Community
  • 1
  • 1
andrewk
  • 381
  • 2
  • 5
7

vim.api.nvim_eval("g:my_var") just evaluates a vimscript expression, so accessing a non-existent variable would error just like in vimscript. Have you tried vim.api.nvim_eval('exists("g:my_var")') instead?


Edit: Using vim.g as @andrewk suggested is probably the better solution as using the dedicated API is more elegant than evaluating strings of vim script.

DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38
  • hi thanks, this worked, it returned 0 or 1 depending on the status, i can use that in the condition – Bmax Dec 21 '20 at 06:00