## 事象
`test.lua`というファイルを作成し、[[Neovim]]で開くと以下のエラーになる。
```error
LSP[lua_ls]: Error ON_INIT_CALLBACK_ERROR: "...dashi-aikawa/.config/nvim/lua/plugins/nvim-lspconfig.lua:226: attempt to index field 'workspace_folders' (a nil value)"
```
[[nvim-lspconfig]]の[[lua-language-server|LuaLS]]に関する設定は以下の通り。
```lua
lspconfig.lua_ls.setup({
capabilities = capabilities,
on_init = function(client)
local path = client.workspace_folders[1].name
if vim.uv.fs_stat(path .. "/.luarc.json") or vim.uv.fs_stat(path .. "/.luarc.jsonc") then
return
end
client.config.settings.Lua = vim.tbl_deep_extend("force", client.config.settings.Lua, {
runtime = {
version = "LuaJIT",
},
workspace = {
checkThirdParty = false,
library = {
vim.env.VIMRUNTIME,
},
},
hint = {
enable = true,
arrayIndex = "Disable",
paramName = "Disable",
semicolon = "Disable",
},
diagnostics = {
groupFileStatus = {
await = "Opened",
},
},
})
end,
settings = {
Lua = {},
},
})
```
## 原因
```lua
local path = client.workspace_folders[1].name
```
の `client.workspace_folders[1]`が`nil`だから。その後の
```lua
if vim.uv.fs_stat(path .. "/.luarc.json") or vim.uv.fs_stat(path .. "/.luarc.jsonc") then
return
end
```
は[[Lua]]プロジェクトの[[.luarc.json]]を探して、存在すれば[[lua-language-server|LuaLS]]はそちらの設定を優先するような記述だが、そもそも[[Lua]]プロジェクトでないと判断された場合が考慮されていない。
## 解決方法
`client.workspace_folders`が存在する場合のみ該当処理を実行するようコードを変更する。
```lua
on_init = function(client)
if client.workspace_folders then
local path = client.workspace_folders[1].name
if vim.uv.fs_stat(path .. "/.luarc.json") or vim.uv.fs_stat(path .. "/.luarc.jsonc") then
return
end
end
```
## 参考
- [nvim\-lspconfig/doc/configs\.md at master · neovim/nvim\-lspconfig](https://github.com/neovim/nvim-lspconfig/blob/master/doc/configs.md#lua_ls)