4

当找不到所需的脚本时,是否可以防止 lua 脚本require失败?

4

3 回答 3

7

这是基本用法

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 开始,不推荐在加载库时设置全局变量,您应该使用 require 的返回值。并且只使用你需要的 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
于 2013-07-26T09:51:23.180 回答
5

在 Lua 中,错误由pcall函数处理。你可以用它包装require

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

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

演示

注意: pcall确实很贵,不应该积极使用。确保,您确实需要静音require失败。

于 2013-07-26T09:09:46.160 回答
1

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

于 2013-07-26T11:18:26.840 回答