DIES
DIES

Reputation: 349

Lua: pcall() doesn't work with coroutine as expected

local function proc_close(a, b)
    _XNO.processList[a] = nil
    if b then panic("process, "..b) end
end

local function proc_load(a)
    local thread = coroutine.create(function()
        os.execute(a)
    end)
    _XNO.processList[thread] = a
    local status, err = pcall(coroutine.resume, thread)
    if not status then
        proc_close(thread, err)
    end
end

proc_load("/some_file")

When it gets to error in executed file pcall() does nothing, error returned as it would be in main code. There is no difference if I pcall() the function in coroutine, or I pcall() the coroutine itself. How Can I catch the error?

Upvotes: 1

Views: 1200

Answers (2)

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

Two issues: (1) os.execute doesn't throw any errors when it fails to execute a command, it returns nil and reports the error, so "resume" completes successfully, (2) you don't need pcall, as resume call already does what's needed to capture the error. Try on the following example:

local thread = coroutine.create(function()
    foo()
  end)
print(coroutine.resume(thread))

This prints false pcall-thread.lua:2: attempt to call global 'foo' (a nil value) for me.

Upvotes: 2

lhf
lhf

Reputation: 72422

pcall does nothing because no error is raised: an error in the executed file does not raise an error in the caller of os.execute. You need to test the return code of os.execute and raise an error if you want.

Upvotes: 1

Related Questions