Lua,改变程序流程当所需文件不存在。

我想测试一下是否有一个 require 的文件存在。

目前,当我在 Lua 中执行此命令时:

require "File_That_May_or_May_Not_Be_There.inc"

如果存在,一切正常。如果不存在,则我的脚本会立即停止运行。

有没有办法让我从中恢复?

我查看了 Lua.Org 网站StackOverflow,但没有看到这个问题的答案。

有没有一种类似这样的方式?...

if (this_exists("That_File")) then
    require "That_File"
else
    print "Your file does not exist"
end

我试图让用户对出错的原因有一个更好的了解。

点赞
用户258523
用户258523

使用pcall

local ok, mod = pcall(require, "That_File")
2014-05-22 18:14:18
用户107090
用户107090

如果你不需要使用 require,它会在多个位置查找模块,你可以使用以下代码:

local f,e=loadfile(filename)
if f==nil then
  print(e)
else
  f()
end
2014-05-22 19:27:52