Lua错误处理

PSk*_*cik 4 error-handling lua

我是lua的新手.

我试过使用 http://keplerproject.github.io/luafilesystem/examples.html ,它会在无法访问的目录上引发错误.

这似乎是由luaL_error https://github.com/keplerproject/luafilesystem/blob/master/src/lfs.c#L563引起的

我怎么能抓到这个错误? http://www.tutorialspoint.com/lua/lua_error_handling.htm 建议pcall,但这并不能阻止脚本死亡:

pcall(lfs.dir('/etc/passwd')) #this fails to handle the not a directory error
Run Code Online (Sandbox Code Playgroud)

Pau*_*nko 5

pcall(lfs.dir('/etc/passwd'))失败,因为错误是在pcall(在计算pcall的参数时)之外触发的.你需要使用

local ok, res = pcall(lfs.dir, '/etc/passwd')
Run Code Online (Sandbox Code Playgroud)

请注意,传递给的参数lfs.dir是给定的pcall,而不是lfs.dir.