Beginner question: control flow in init.lua for first run?

As a newcomer to writing my init in lua, how should I fence off things that require something present? For example, the first time I run on a new system, I need ‘lspconfig’ installed before require'lspconfig'... will work and as such my init lua won’t run at all (to workaround I removed everything put the paq stuff untill i could PaqInstall and then add it back in).

How should I be writing control flow around that so it only tries to execute that section if it exists?

1 Like

You can just check for the return value of require, like so:

local lspconfig = require'lspconfig'
if lspconfig then
    lspconfig.setup() -- or whatever you need to do
end

Ha! Thanks. Didn’t realise it would be so straightforward :flushed:

You should actually wrap require in pcall else it’ll fail when lsoconfig isn’t installed

local ok, lspconfig = pcall(require, 'lspconfig')

if ok then
  -- Whatever you want to do with lspconfig
end
1 Like

Ahhh right, I kinda ignored that require errors and doesn’t just return nil. Good thing, too… thanks for the correction!

I’ve read about the [pcall](https://www.lua.org/pil/8.4.html) here (protected) so understand what that is doing, but could you explain what the ok is doing here? Is ok, basically a ‘truthy’ test for what comes after?

But if I want to check another require, does the if ok then know which to apply to?

Sorry – I did mention I was a beginner to this!

pcall returns two values, the first one will be a boolean stating whether the call succeeded or failed and the second will be the return value of the call. It could be nil which means the call did not return anything.

To answer your main question, I did a bit of brainstorming a few days ago and came up with a simple solution to check if the plugin manager is installed or not. If not, then install it and all the plugins using the plugin manager command and quit Neovim after that. I use packer.nvim and the problem is that all commands are asynchronous, so I had to work around for that and create an infinite loop which will wait until the command PackerSync is complete.

You can check it out here (details are documented): dotfiles/packer.vim at master · dhruvmanila/dotfiles · GitHub

2 Likes

I was actually looking for a solution for this as well, and I’ve wrapped all my requires with pcall, however I am wondering whether there is a simpler way. Otherwise wherever I need to require things I’d have to do this and it feels like this is just too much just for the first setup to go smooth, whereas I could basically let it fail the first time and it’d be fine after run nvim the second time.

You can see in my dotfiles that all of the config starts with that clause basically.