Adrian Costin
Adrian Costin

Reputation: 438

changing global variable value neovim

I am trying to define a custom lua configuration for the nvim-qt GUI. In order to do so, I would first like to toggle fullscreen on and off, but I encounter some pretty weird behavior.

vim.g.nvim_qt = {
    fullscreen = false,
    fontsize = 14,
    font_name = 'Iosevka\\ NF:h'
}

local toggle_fullscreen = function ()
    vim.g.nvim_qt.fullscreen = not vim.g.nvim_qt.fullscreen

    if vim.g.nvim_qt.fullscreen then
        return '1'
    else
        return '0'
    end
end

--vim.cmd('call GuiWindowFullScreen(' .. toggle_fullscreen() ..')')
vim.keymap.set('n', '<F11>', ':call GuiWindowFullScreen(' .. toggle_fullscreen() ..')<CR>')

What I would expect, is the value of fullscreen to be toggled on each function call. It however always remains false. Can anyone explain why this happens?

Upvotes: 1

Views: 3546

Answers (2)

matt0089
matt0089

Reputation: 471

I ran into trouble with the following code:

function toggle(key)
  vim.g.my_map[key] = not vim.g.my_map[key]
end

The global variable wasn't updating. The docs were great though, they explained it clearly (:h lua-vim-variables)

Note that setting dictionary fields directly will not write them back into
Nvim. This is because the index into the namespace simply returns a copy.
Instead the whole dictionary must be written as one. This can be achieved by
creating a short-lived temporary.

Example:

    vim.g.my_dict.field1 = 'value'  -- Does not work

    local my_dict = vim.g.my_dict   --
    my_dict.field1 = 'value'        -- Instead do
    vim.g.my_dict = my_dict         --

This fixed it:

function toggle(key)
  local temp = vim.g.my_map[key]
  temp[key] = not vim.g.my_map[key]
  vim.g.my_map = temp
end

Upvotes: 5

Evert_B
Evert_B

Reputation: 293

I'm not 100% familiar with the Neovim-qt framework, but your toggle_fullscreen() function does seems to work fine. When running this locally, I get the toggling behavior.

Could you provide some more information how the keymap exactly works? My guess is that the set() function simple runs the toggle_fullscreen once and saves it in the keymap as ":call GuiWindowFullScreen(0)", which leads you to always calling the function with a false value.

Upvotes: 1

Related Questions