Is it possible to prevent a lua script from failing when a require
fails to find the script required?
This is basic usage
if pcall(require, 'test') then
-- done but ...
-- In lua 5.2 you can not access to loaded module.
else
-- not found
end
But since Lua 5.2 it is deprecated set global variables when load library you should use returned value from require. And using only pcall you need :
local ok, mod = pcall(require, "test")
-- `mod` has returned value or error
-- so you can not just test `if mod then`
if not ok then mod = nil end
-- now you can test mod
if mod then
-- done
end
I like this function
local function prequire(m)
local ok, err = pcall(require, m)
if not ok then return nil, err end
return err
end
-- usage
local mod = prequire("test")
if mod then
-- done
end
In Lua errors are handled by pcall
function. You could wrap require
with it:
local requireAllDependenciesCallback = function()
testModul = require 'test';
-- Other requires.
end;
if pcall(requireAllDependenciesCallback) then
print('included');
else
print('failed');
end
Demo
Note: pcall
is really expensive and should not be actively used. Make sure, you really need to mute require
fails.
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