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.

2 Answers 2

13

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!

Sign up to request clarification or add additional context in comments.

2 Comments

This method is not correct: a global variable can take a value of false, then the checking condition is invalid.
Updated the condition to be an explicit nil check.
9

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.

1 Comment

hi thanks, this worked, it returned 0 or 1 depending on the status, i can use that in the condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.