模块化Neovim配置中扩展nvim-lspconfig服务器列表失败,报错Expected table, got nil
模块化Neovim配置中扩展nvim-lspconfig服务器列表失败,报错Expected table, got nil
嘿,我来帮你排查这个问题~你遇到的Expected table, got nil错误主要是因为几个配置逻辑上的小问题,我一步步给你拆解:
问题根源分析
opts.ensure_installed初始为 nil:在你的lsp.lua里,nvim-lspconfig的opts被设为空表{},而你是在config函数里直接调用require('mason-lspconfig').setup来设置ensure_installed的。这就导致当你在go.lua的opts函数里访问opts.ensure_installed时,它根本不存在,是nil,自然会报错。- 错误使用
vim.tbl_keys:这个函数的作用是提取表的所有键并返回一个数组,而不是用来向表中添加元素。你想用它添加gopls完全搞错了用法。
修正方案
我们需要调整两个文件的配置,让模块化的配置能正确合并LSP服务器:
第一步:修改lsp.lua,把mason-lspconfig的配置移到opts里
这样后续的模块化文件才能通过opts来扩展配置,而不是直接在config里硬编码:
{ 'neovim/nvim-lspconfig', branch = 'master', event = { 'BufReadPost', 'BufNewFile', 'BufWritePre' }, dependencies = { 'williamboman/mason.nvim', 'williamboman/mason-lspconfig.nvim', { 'j-hui/fidget.nvim', opts = {} }, }, -- 把mason-lspconfig的配置移到opts里,方便后续扩展 opts = { servers = { lua_ls = { Lua = { workspace = { checkThirdParty = false }, telemetry = { enable = false }, diagnostics = { globals = { 'vim' }, }, }, }, }, mason = { ensure_installed = vim.tbl_keys({ lua_ls = {}, }), }, }, config = function(_, opts) local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').default_capabilities(capabilities) local on_attach = function(_, bufnr) -- 你的快捷键映射保持不变 end -- 遍历servers配置来设置LSP for server_name, server_opts in pairs(opts.servers) do require('lspconfig')[server_name].setup(vim.tbl_deep_extend('force', { capabilities = capabilities, on_attach = on_attach, }, server_opts)) end -- 初始化mason-lspconfig require('mason-lspconfig').setup({ ensure_installed = opts.mason.ensure_installed, }) end, }
第二步:修正go.lua的配置,正确扩展服务器列表
现在我们可以通过opts函数来合并Go相关的LSP配置了:
-- mason和treesitter的配置保持不变 { "neovim/nvim-lspconfig", opts = function(_, opts) -- 添加gopls到servers配置 opts.servers.gopls = {} -- 如果需要自定义gopls的设置,可以在这里写,比如settings字段 -- 把gopls添加到ensure_installed列表 table.insert(opts.mason.ensure_installed, 'gopls') end, }
额外说明
如果你需要给gopls添加自定义配置,比如设置Go的分析选项,可以这样写:
opts.servers.gopls = { settings = { gopls = { analyses = { unusedparams = true, }, staticcheck = true, }, }, }
这样调整后,你的模块化配置就能正确合并LSP服务器,不会再出现nil相关的错误啦~
备注:内容来源于stack exchange,提问作者John Snape
相关产品推荐
相关产品推荐

