Lua / nvm-lspconfig : on_attach handler with local scope causes issue

I am new to lua and LSP and just copied the suggested configuration from GitHub - neovim/nvim-lspconfig: Quickstart configs for Nvim LSP.

Problem: The on_attach handler has not been invoked. After an hour of investigation, I found out, the cause is the local scope of the on_attach handler function.

In other words, this worked:

function on_attach(client, bufnr)
...
end

This not:

local function on_attach(client, bufnr)
...
end

Minimal example:

-- ~/.config/nvim/lua/plugins.lua
local lsp_flags = {
  debounce_text_changes = 150,
}

function on_attach(client, bufnr)
    local bufopts = { noremap=true, silent=true, buffer=bufnr }
    vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts)
    -- ... more keybindings and configuration omitted here
end

return require('packer').startup(function(use)
  use 'wbthomason/packer.nvim'
  use {
    'neovim/nvim-lspconfig', 
    config = function()
      require'lspconfig'.pyright.setup ({
	on_attach = on_attach,
        flags = lsp_flags,
      })
    end
  } 
end)

Might be anybody so kind to explain, what the difference is in this context?

This seems to be an issue with the scope of local lua variables in my config.

I am still baffled, as I just combine sample configs from packer.nvim and nvm-lspconfig, where also local is used.

Further attempt: Placing

local lspconfig = require'lspconfig'

at top of the script and changing references like this further down:

config = function()
        lspconfig.pyright.setup {
            on_attach = on_attach,
            flags = lsp_flags,       
        }      

will report

packer.nvim: Error running config for nvim-lspconfig: [string “…”]:0: attempt to index upvalue ‘’ (a nil value)

, so this again speaks for the local scope issue.

Note, that I am including the .lua file in ~/.config/nvim/init.vim:

lua require('plugins')

Any comments appreciated.

It is actually an issue with packer.nvim.

See GitHub - wbthomason/packer.nvim: A use-package inspired plugin manager for Neovim. Uses native packages, supports Luarocks dependencies, written in Lua, allows for expressive config for more info.