Why is defining a local table and returning it a good practice?

I’m moving from a vimscript-based config to a lua-based one. I’ve noticed the following pattern in several lua-based configs from other people that I’m using as reference:

local vim = vim
local M = {}

M.setup = function()
-- code
end

return M

and then they call the function stored in the table that is returned, e.g.:

require('mrv.settings').setup()

My question is, why is this approach useful? Other lua-based configs I’ve seen, use the more vimscript-based way of writing the code in the global scope and sourcing the whole file. Is there any advantage of the table-based approach with respect to the global-based one?

1 Like

require function will cache it on a first call then if you call it again it will not load that file more. if you use luafile or source to load it from vimscript it still load it when you call it again.
`
return a table because you can reuse it with a cache version on a first require.

2 Likes