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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With