Book Image

Integrate Lua with C++

By : Wenhuan Li
Book Image

Integrate Lua with C++

By: Wenhuan Li

Overview of this book

C++ is a popular choice in the developer community for building complex and large-scale performant applications and systems. Often a need arises to extend the system at runtime, without recompiling the whole C++ program. Using a scripting language like Lua can help achieve this goal efficiently. Integrate Lua to C++ is a comprehensive guide to integrating Lua to C++ and will enable you to achieve the goal of extending C++ programs at runtime. You’ll learn, in sequence, how to get and compile the Lua library, the Lua programming language, calling Lua code from C++, and calling C++ code from Lua. In each topic, you’ll practice with code examples, and learn the in-depth mechanisms for smooth working. Throughout the book, the latter examples build on the earlier ones while also acting as a standalone. You’ll learn to implement Lua executor and Lua binding generator, which you can use in your projects directly with further customizations. By the end of this book, you’ll have mastered integrating Lua into C++ and using Lua in your C++ project efficiently, gained the skills to extend your applications at runtime, and achieved dynamic and adaptable C++ development.
Table of Contents (18 chapters)
Free Chapter
1
Part 1 – Lua Basics
4
Part 2 – Calling Lua from C++
8
Part 3 – Calling C++ from Lua
12
Part 4 – Advanced Topics

How to register C++ functions

Lua is written in C, so it cannot access your C++ classes directly. The only way to call C++ code from Lua is to make it call C++ functions – that is, plain C functions.

How to declare C++ functions for Lua

To register a function to Lua, it must conform to the following prototype:

typedef int (*lua_CFunction) (lua_State *L);

The function receives only one argument, which is a Lua state. It needs to return an integer value indicating how many return values it produces. The Lua state is private to the function call, and its stack holds the arguments passed from the Lua code when calling the C++ function. The C++ function needs to push its return values onto the stack.

We will first implement a simple function and export it to Lua. Then, we’ll see more complex examples to understand more.

Implementing your first C++ function for Lua

Let us add a simple but useful capability to our Lua executor. It will provide a function...