- Lua Game Development Cookbook
- Mário Ka?uba
- 366字
- 2021-07-16 13:23:07
Handling errors with pcall, xpcall, and assert
By default, the Lua language uses its internal error function. If an error occurs, Lua will usually abort code execution and put the error message with trace back into the standard error output. You can override the standard behavior with the pcall
and xpcall
functions. The main difference between these two functions is that pcall
will return the status code and error message as the second return value, and xpcall
will use the user-defined error function.
This way you can catch nonfatal errors and emulate the try
and catch
block.
Getting ready
This recipe will show error handling on a simple function that can exit prematurely with the error message:
local function f1(a, b) assert((a == 1), "The first parameter must be equal to 1") print(b) return a+1 end
How to do it…
Here's how you can catch a nonfatal error with pcall
by emulating the try
and catch
block:
function try(fn, catch_fn) local status, msg = pcall(fn) if not status then catch_fn(msg) end end try(function() f1(2, 3) -- this will throw "an exception" end, function(e) print('An exception occured:', e) error('Throw exception') end)
The next recipe shows how to create your own specialized xpcall2
function that can handle input parameters for a function:
local function xpcall2(fn, ...) local arg = {...} return xpcall( -- function wrapper to pass function arguments function(...) return fn(unpack(arg)) end, -- error function function(msg) return debug.traceback(msg, 3) end ) end print(xpcall2(f1, 2, 'a'))
How it works…
The whole principle of the try
and catch
block emulation in Lua relies on the pcall
function that catches the error message and pushes it into the catch
block function.
The only weakness of this approach is that you can't get more information because you're handling errors outside of the scope of where the error occurred.
This issue can be solved with xpcall
which handles error before stack unwinding so you can use the debug library to get more information about the error.
Xpcall2
works as a wrapper function that not only passes parameters into protected function calls, but also handles getting the trace back with the debug.traceback
function and returns results or a status code with an error message.
- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- C語言程序設計
- Web Application Development with MEAN
- Mastering Google App Engine
- Mastering C++ Multithreading
- Hadoop 2.X HDFS源碼剖析
- Laravel Application Development Blueprints
- PHP 8從入門到精通(視頻教學版)
- 進入IT企業必讀的324個Java面試題
- Getting Started with Electronic Projects
- C語言從入門到精通
- jQuery Mobile Web Development Essentials(Second Edition)
- 從零開始構建深度前饋神經網絡:Python+TensorFlow 2.x
- 網頁設計與制作
- Building Clouds with Windows Azure Pack