Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Lua Game Development Cookbook

You're reading from   Lua Game Development Cookbook Over 70 recipes that will help you master the elements and best practices required to build a modern game engine using Lua

Arrow left icon
Product type Paperback
Published in Jul 2015
Publisher
ISBN-13 9781849515504
Length 360 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Mário Kašuba Mário Kašuba
Author Profile Icon Mário Kašuba
Mário Kašuba
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Basics of the Game Engine 2. Events FREE CHAPTER 3. Graphics – Common Methods 4. Graphics – Legacy Method with OpenGL 1.x–2.1 5. Graphics – Modern Method with OpenGL 3.0+ 6. The User Interface 7. Physics and Game Mechanics 8. Artificial Intelligence 9. Sounds and Networking Index

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime