pcall and error

Lua's most efficient way to handle errors is pcall, or protected call. The pcall function takes only one argument, the function to be called. Optionally, if the function takes arguments, they should also be passed to pcall as additional arguments. On success, it returns true and all of the values the function would normally return. On failure, it returns false, and any error messages that need to be returned as well.

When an error happens, the error function can be used to stop the execution of the current method. The error function expects only one argument (and even that's optional): an error message. This message can be a string, but doesn't have to be. The error message can be any valid value. The code here shows a simple use for pcall  and error:

function Normalize(x, y, z) 
local dot = x * x + y * y + z * z
if dot == 0 then
error("Can't normalize zero vector")
end
local len = math.sqrt(dot);
return x / len, y / len, z / len
end

local ok, x, y, z = pcall(Normalize, 0, 0, 0)
if not ok then
print ("Error occured normalizing vector")
print ("Error message: " .. x)
else
print ("Vector normalized")
end
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.64