assert

Errors raised with pcall do not interfere with the stability of the program. When an error can be recovered from, it should be handled with pcall. But, if an error is catastrophic, it should be handled with assert. Unlike pcall, assert assumes an error is not recoverable and will simply kill the program.

The assert function takes two arguments, a test value and a string. If the test value evaluates to false or nil, assert will kill the program. If the test value evaluates to anything else, it is returned. The second argument is a string. This string will be printed out as the reason that the program has failed executing. The normalize example can be re-written to use an assertion, like so:

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

local x, y, z = Normalize(0, 0, 0)
print("normalized vector")
..................Content has been hidden....................

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