2013-07-26 32 views

回答

3

在Lua中,错误由pcall函数处理。你可以换require它:

local requireAllDependenciesCallback = function() 
    testModul = require 'test'; 
    -- Other requires. 
end; 

if pcall(requireAllDependenciesCallback) then 
    print('included'); 
else 
    print('failed'); 
end 

Demo

注:pcall真的很贵,不应该积极使用。确保,你真的需要静音require失败。

+0

感谢PLB,这是有效的。当你说它不应该被主动使用时,纯粹是从性能角度还是其他问题? – MarkNS

+0

@ MarkNuttall-Smith仅限演出。如果你决定为此使用'pcall'。我会建议创建一些函数来处理所有需要避免太多'pcall's。例如:'local requireFiles = function() - 在这里需要。结束;'并将其传递给'pcall'。 – Leri

+0

实际上我并不关心性能,因为它只是在应用程序启动期间,我会这样做。我希望能够在用户特定的目录或共享位置中找到依赖关系。再次感谢。 – MarkNS

6

这是基本用法

if pcall(require, 'test') then 
    -- done but ... 
    -- In lua 5.2 you can not access to loaded module. 
else 
    -- not found 
end 

但由于Lua的5.2它已被弃用设置全局变量时加载库从需要你应该使用返回的值。 而只有使用PCALL您需要:

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 

我喜欢这个功能

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 
+0

最后一个真的是_sweet_。语言本身应该是这样的。我不喜欢的是每个'prerequire'都会调用'pcall'。 – Leri

+1

我不认为这是个大问题。 cfunction'pcall'调用cfunction'require'。 – moteus

+0

我也想在标准库中看到这个功能。也作为允许从列表中加载一个库的函数('bit = vrequire(“bit32”,“bit”)')。 – moteus

1

而不是使用pcall,你在加载器列表的末尾添加可以在自己的装载机,并让这个你的loader不会失败,而是返回一个特殊的值,比如一个字符串。然后,您可以正常使用require并只检查其返回值。 (装载机现在在5.2中称为搜索者。)

+0

但这是影响到所有模块,这可能是一个很大的惊喜,即'需要'返回无效值。 – moteus