This book covers integration between the Lua and C languages with emphasis on building a user-facing API. Your API might be used to speed up development within your company; it might be released to customers as a way to customize your app or game; and it could be used as the foundation of a domain-specific language within a platform you’re developing.
Although in some contexts the term API implies web-based interaction, such as a RESTful HTTP-based interface, this book is not about this type of API; rather, it’s about creating a set of Lua classes and functions used to programmatically work with a local application.
This book is split into two parts: Part I, Making a Lua API, describes how C and Lua can interface with each other, whereas Part II, Script Safety, explains how to safely run scripts written by users who might make mistakes or might even purposefully attempt to break your system. Not very nice! But this book will help to prepare you for issues like this.
Chapter 1 covers building Lua from source as well as linking the Lua library into a C program that can execute a Lua script. Chapter 2 dives into the mechanics of calling C functions from Lua—effectively giving you a way to write Lua-visible functions with the power to do anything C can do. Chapter 3 explores the use of Lua data types from C. Chapter 4 explains how to add classes to your API, whether they’re implemented in either Lua or C. In the second part of the book, Chapter 5 shows you how to handle Lua exceptions with error-handling functions as well as how to protect yourself against questionable uses of global variables. Finally, Chapter 6 explains the idea of sandboxing a potentially harmful script, which makes it possible for you to safely run Lua scripts without having to fully trust the authors of those scripts.
My editor, Dawn Schanafelt, did an amazing job of transforming my ramblings and ill-fated attempts at humor into the less-rambly, hopefully slightly amusing technical book you see before you. Joël Franusic was extremely helpful in finding many of my technical opportunities for improvement (bugs) and added a great deal of clarity to the code and details thereabouts. Susan Conant initiated the entire project and made it happen.
Kudos are due to my wife, Jean Hsu, who put up with many working evenings and even took over a few household chores while I typed away. My kids, Alina and Jackson, provided excellent motivation to be a maker and a teacher. My dog, Kepler, contributed nothing whatsoever to this book, but he seems to like me and doesn’t really get mentioned in many acknowledgments, so I thought I’d throw his name in the mix. Finally, I would like to express my gratitude to all my direct genetic ancestors, without whom I would not exist.