如何在`require`未能找到所需的脚本时避免Lua脚本失败?

是否有可能在需要的脚本没有被找到时,防止 lua 脚本执行失败?

点赞
用户1283847
用户1283847

在 Lua 中,错误是通过 pcall 函数处理的。你可以将 require 包装在其中:

local requireAllDependenciesCallback = function()
    testModul = require 'test';
    -- 其他的 requires
end;

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

演示

注意:pcall 的性能非常低,不应该经常使用。确保你 真正需要 静音 require 失败。

2013-07-26 09:09:46
用户2328287
用户2328287

这是基本的用法

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` 返回值或错误
-- 所以你不能仅测试 `if mod then`
if not ok then mod = nil end
-- 现在你可以测试 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

-- 使用
local mod = prequire("test")
if mod then
  -- done
end
2013-07-26 09:51:23
用户107090
用户107090

代替使用 pcall 函数,你可以将自己的加载器添加到加载器列表的末尾,并使其不会失败,而是返回一个特殊的值,如字符串。然后你可以正常使用 require 函数,只需要检查其返回值即可。(在 5.2 中,加载器现在被称为搜索器。)

2013-07-26 11:18:26