Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to add lua to c++?

2 Answer(s) Available
Answer # 1 #

There is the various reason for choosing Lua to provide the scripting support:

Despite all the above advantages, Lua provides a very low-level C API which requires the developer to learn the internals of the Lua engine before he can use it in the applications. However, this has changed with the Lua Cpp library.

LuaCpp: It is a lightweight wrapper for Lua C APIs that provides access to the Lua library of two levels i.e., Accesses through high-level APIs that are hiding the complexity of the C APIs and the engine, and access to the Lua low-level APIs.

The LuaCpp can be installed as a system-wide library, or as a sub-module of your exiting project. Run the below command to install the LuaCpp in ubuntu.

Once the library is installed, build the file as follows:

Output the file as:

Below is the same program to illustrate the same:

Output:

The example is showing us how to compile and execute Lua code snippet from C++. However, without the ability to pass data from C++ to Lua, and back from Lua to C++, there are not many real-life cases that can be addressed by this pattern.

LuaCpp arrives prepared to establish the bridge between the two execution environments wilt as little as possible knowledge of the internal working of Lua, as well as with minimal code. Let’s improve the “Hello World” example by adding a variable that will be shared by both execution environments. This introduces a “String” variable called “world” and populates it with a value from the C++ context. Inside the Lua context, update the value of the variable, and upon return to the C++ context and print the value of the variable.

Below is the program to illustrate the same:

Output:

The context allows passing multiple variables from the C++ scope to Lua scope and vice versa. The above pattern allows for adding the scripting support to the C++ project for the majority of the cases. The simple 4-step process is:

The LuaCpp provides the following types of variables that can be passed between the C++ and Lua context:

[2]
Edit
Query
Report
Tinu Naval,
CARVER HAND
Answer # 2 #

Conceptually, the common steps to enable scripting are the following (I will be using pseudo-c for the host and pseudo-lua for the script. These are not exact steps, but more like the general flow in which you enable scripting)

That's all there is to it. The program then flows in the following manner:

So in general, all you're doing is running a program inside another program. Theoretically speaking, there is nothing you can do with scripts that you can't do without them, but this abstraction allows you to do some interesting things really easily. Some of them are:

[2]
Edit
Query
Report
Trisha Diggity
KILN OPERATOR MALT HOUSE