Vim global variable check throws error in lua (neovim plugin development)
Asked Answered
A

2

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.

Adventurer answered 21/12, 2020 at 5:7 Comment(0)
D
8

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.

Deleterious answered 21/12, 2020 at 5:44 Comment(1)
hi thanks, this worked, it returned 0 or 1 depending on the status, i can use that in the conditionAdventurer
T
11

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!

Tradelast answered 12/1, 2021 at 7:7 Comment(2)
This method is not correct: a global variable can take a value of false, then the checking condition is invalid.Haywire
Updated the condition to be an explicit nil check.Tradelast
D
8

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.

Deleterious answered 21/12, 2020 at 5:44 Comment(1)
hi thanks, this worked, it returned 0 or 1 depending on the status, i can use that in the conditionAdventurer

© 2022 - 2024 — McMap. All rights reserved.