▲ | thayne 5 days ago | |
I don't know that I would call it an anti-pattern. It has several advantages over using a global variable: - it avoids needing to create a global variable in the top level namespace - if the setup is called lazily, then the user config can also perform other lazy operations at configuration time, including requiring other lua modules - it allows you to pass a config object or function to your package manager, thus keeping your configuration of a plugin, and the code to require the plugin in the same place. - it doesn't have the problem that you have to make sure you set the global variable before the plugin is loaded - it is simpler to handle reconfiguring at runtime. The user just calls setup again. Whereas with a global variable, you don't know if/when the config has changed | ||
▲ | mrcjkb 5 days ago | parent [-] | |
- It's not at the top level namespace, it's usually in the `vim.g` or `vim.b` namespace. There's no more namespacing than with a Lua module + function. - global configuration variables don't have to be tables. They can be a union of `table | fun():table`, which enables laziness. [rustaceanvim does this, for example](https://github.com/mrcjkb/rustaceanvim/blob/12504405821c0587...). - lazy.nvim's heuristics to auto-detect and invoke `setup` functions and pass "config objects" are a hack that could just as easily have been implemented around global config variables. This is a symptom of the problem, not a solution. - If you don't need any code to require the plugin, there's also no need to keep the configuration and the code to require it in the same place. - If a plugin is implemented correctly (by not making lazy loading the responsibility of the user), there's no need to worry about when the user sets the global variable. - Most plugins' `setup` functions are idempotent. If you want to provide the ability to reconfigure your plugin at runtime, you can provide a `reload(opts)` function that sets the global config variable and then reinitialises the plugin. Or, you could add a metatable to the config variable that triggers a reload if the plugin has already been initialised. There's hardly ever a valid reason to force the coupling of configuration and initialisation on your plugin's users. |