Lua pcall

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

If you want to run a Lua code, the code in the running process can catch exceptions and errors of all.

1, Encapsulating this code in a function

function foo()
    if x > y then
        error()
    end
    
    print(a[i])
end

2, Use pcall to call this function

if pcall(foo) then
    -- no errors
else
    -- 'foo' raised an error
end

Can also use anonymous functions call pcall

if pcall(function () ... end) then
    ...
else
    ...
end

Pcall cut and run in protected mode with its first parameter, so we can catch the exception and error all. If there are no exceptions and errors, any value pcall to return the true and the call returns; otherwise returns nil plus the error message.

The error message is not a string, any information passed to error will be returned by pcall.

local status, err = pcall(function () error({code = 121}) end)
print(err.code) -- Output: 121

This mechanism provides us with exceptions and errors of all the content in Lua. We use error throws an exception, then the pcall capture.



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Sheryl at October 03, 2014 - 3:15 PM