How to check if a module exists in Lua?
lua
Solution
If you need to distinguish between a missing module and a syntax error, you can directly access the searcher functions in `package.searchers`.
These functions will:
- Return a loader function if successful
- Return a string if the module is not found
- Throw an error if there is a syntax error
So what you can do is mimic the way `require` searches for a module, calling each searcher in turn until one of them returns a function. Unlike `require`, we need not throw an error if the module is not found, i.e. if every searcher function returns a string.
function isModuleAvailable(name)
if package.loaded[name] then
return true
else
for _, searcher in ipairs(package.searchers or package.loaders) do
local loader = searcher(name)
if type(loader) == 'function' then
package.preload[name] = loader
return true
end
end
return false
end
end
Problem
I'm using xdg-menu-to-awesome-wm to generate a Lua file containing the GNOME menu, for inclusion in Awesome WM. Since the generator script may not be installed, I need some way for Lua to only `require` the `menu` module if it exists. I don't want to go looking through file names, since it could be anywhere in `package.path`. One option would be to ignore the exception created when the module does not exist, but I'd rather not ignore any other exceptions - I do want to know if the module contains any syntax or other errors. The reference unfortunately doesn't specify which exceptions can be generated, so I'm not sure how to do it.