DIES
DIES

Reputation: 349

pcall() ignores os.execute() error

I'm working on a error handling and it almost works, but fails on the most important step.

In this file, "KAImage.lua" I have an syntax error (= vs ==) and when example function below

print(status, err = pcall(os.execute, "/System/Library/Frameworks/Kakao.framework/KAImage.lua"))

called it gives me error with traceback and right after it true true, so means pcall() absolutely ignores exception.

Script execution doesn't stops and I can't really see where is the problem.

Upvotes: 0

Views: 995

Answers (2)

Alexander Altshuler
Alexander Altshuler

Reputation: 3064

Your code snippet has the syntax error, correct code should looks like below:

local status, err = pcall(os.execute, "/System/Library/Frameworks/Kakao.framework/KAImage.lua")
print(status, err)

I don't think that executing a Lua file using os.execute is a good idea. It would work with proper shebang, but will spawn separate process(es).

IMO that you need is dofile(lua_file_name):

Opens the named file and executes its contents as a Lua chunk. ... Returns all values returned by the chunk. In case of errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode).

It is a job of pcall to catch errors, if you do need to catch error you may use code like below:

local chunk, err = loadfile(lua_file_name)
if not chunk then
    -- invalid Lua code, check err
    return
end
local ok, err = xpcall (chunk, debug.traceback))
if not ok then
    -- error was catched, err contains detailed stack info and error description
    return
end
-- success

Upvotes: 1

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

os.execute doesn't raise any error when it fails to execute the command; it returns nil as the first value to signal an error along with some additional values, as described in the manual.

Upvotes: 1

Related Questions