- How To Integrate Lua With C++
- How To Embed Lua In C Program
- How To Integrate Lua With Css
- How To Integrate Lua With Computer
- How To Integrate Lua With Chrome
- How To Embed Lua In C++
Luais a popular scripting language due to its tight integration with C. LuaJITis an extremely fast JIT compiler for Lua that can be integrated into your game, which also provides an FFI Librarythat directly interfaces with C functions, eliminating most overhead. However, the FFI library only accepts a subset of the C.
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. How to install Lua? This code helps to bind the C object into a Lua object with the alias ‘CppObject. Lets dissect the code line by line. This line defines the new Lua Usertype and also defines the member function ‘TestFunction1’ to specify that the class contains this function. In this line, we create a new object ‘cppObj’ of type ‘CppObject’. The first step is to define the function. All C or C functions that will be called from Lua will be called using a pointer of this type: typedef int (.luaCFunction) (luaState.L); In other words, functions must have a Lua interpreter as the only argument and return only an integer. Since a Lua interpreter is used for the argument, the. Start - Script: script.lua print('I am using Lua from within C') - End There, told you it was a very basic script! When we embed Lua into C, we will ask Lua to open and run that file. For more examples, see the end of the tutorial. Now for the C code. Create a new text file called and save it as 'embed.c'.
Lua has a very simple C API. You can run Lua code and access lua objects from C. Similarly, you can access C functions and libraries from Lua. In this post, we’ll primarily look at how to expose C functions to lua.
Let’s start off with the installation of lua. You can install lua using system package managers as
You can also build lua from source. However, you have to build lua as a shared library and this can be a bit tricky.
Communication between lua and C is held through stacks with each element in stack representing lua value (nil, number, string, etc.).
For example, a C wrapped function
c_swap is called in lua as:
In C, you will receive arguments in a stack as
You will then read the arguments from the stack as (indexing for this stack starts with 1 like in lua):
This is actually unsafe because these calls will fail if value in the stack at the specified index is not a number. Following code uses auxiliary library
lauxlib.h and is safer; it will raise errors instead of segfaulting.
Then, you will process the arguments and push the results to stack.
Stack will now look like
Since you need to communicate the number of return value to lua, you will
return 2. Lua will then know that top 2 values in the stack are the returned values.
The stack we’ve described is not global. Each function has its own stack.
How To Integrate Lua With C++
How To Embed Lua In C Program
Let’s put all this together into
main() function illustrates how to run lua code from C.
And build and execute as If you have installed lua with apt-get, build using
gcc main.c -o swap -llua5.2 -I/usr/include/lua5.2/
which should print
In the above code, you’ve not really used lua interpretor; you’ve run the lua code in C itself.You might rather want to create a module which you can load into a lua interpretor using
To do this, you’ll have to register your functions by creating a array of
luaL_Reg and a function
Let’s do this right away by editing
main.c. We will also add additional
This code works only for lua 5.2. For lua 5.1, please use
luaL_register(L, 'mylib', mylib); instead of
Create a loadable
.so file with
If you have installed lua with apt-get, build using
gcc main.c -shared -o mylib.so -fPIC -llua5.2 -I/usr/include/lua5.2/
You can now load this module in lua.
Now, you should be able to wrap any C library by writing a lua wrapper.We still have some caveats:
- We will have to write a wrapping function for each of the functions in your C library to ‘parse’ the arguments(
luaL_checknumberetc.). This is repetitive and can be a potential source for bugs.
- C doesn’t have classes. What if your library is in C++? You cannot easily wrap classes like above. You will have to mess with metatables and so on.
A solution to both of these is to use Swig. Swig allows you to wrap C/C++ classes/functions into many languages like python, lua, java quite easily. In a later post, we will see how to use swig and wrap a simple library.
This post contains a full managed lua wrapper around the lua API, a simple script engine making life easier when communicating with lua, a sample class ‘NPCPlayer’ to integrate with lua, a sample program using the script engine and the sample class and last a basic explanation of the lua stack.
Hopefully the post will fill in the gaps from part I and II and I will provide all the working source code to illustrate lua embedding.
All files referenced in this post can be downloaded as a zip file found here.
The source code contains lots of useful comments as well.
A full managed lua wrapper
The managed wrapper is defined in its completeness in the static class ‘Lua’
This class wraps all the lua c functions and constants, and bridges the integration to the natively compiled lua.dll.
The wrapper class can be found in the zip file in the introduction of the post.
A simple Script engine – how to use the managed wrapper
The wrapper is basically just a 1-1 bridging of the full lua API and constants.
To use it you will therefore need to understand how the various lua API functions work.
Most of the functions exposed through lua API operate on the lua stack.
To make life easier in communicating with lua through the stack, I have made a simple script engine class that has methods that encapsulates the lua API calls for some of the things you’ll often have to do.
- Instantiating lua and managing the lua state.
- Error logging with messages from lua interpreter
- Registering C# methods with lua
- Creating a lua table
- Getting and setting table fields
- Pushing and popping values on the lua stack
- Running a script file
The script engine class can be found in the zip file in the introduction of the post.
I have made a small console app to demonstrate the use of the scriptengine together with a sample class ‘NPCPlayer’.
The app consists of a single class ‘Program’ in a single file.
The demonstration program class and the NPCPlayer class can be found in the zip file in the introduction of the post.
The lua stack
The single most important thing when extending your application with lua is to understand how the lua stack works, and how exactly you use it to communicate with lua.
Stack data structure
A stack data structure is a general structure used in many different languages to solve various computing problems.
If you do not know yet what a stack structure is and how it works, you should start by looking at an explanation here.
As you can see a stack data structure is kind of a tower of data elements stacked on top off each other.
When a new data element is put on top of the stack it is called a PUSH operation.
When the top element of the stack is removed, it is called a POP operation.
PUSH and POP always operate from the top of the stack.
The stack is also called a LIFO structure (last in first out) because of how the operations on the stack function.
As a starting example I will explain the lua API function calls used in the script engines method ‘CreateLuaTable’
The lua stack will be empty after opening lua, and the ‘CreateLuaTable’ assumes an empty stack as well.
The method looks like this and takes a single string parameter containing the name of a lua table to create in lua.
First I use lua_getglobal to check if the table already exists.
Lua_getglobal PUSHES the lua table onto the lua stack if the table did exist, else it will leave the stack with a nil value on top.
How To Integrate Lua With Css
I then check if the top of the lua stack is nil, if it is the table did not exist and I will create it.
I POP the nil value off the stack with lua_pop, that takes as argument how many elements to pop.
Stack is now again empty.
How To Integrate Lua With Computer
I then create a new lua table with lua_newtable which PUSHES the new lua table object onto the stack
A single table element is now sitting on top of the stack.
Then I set the name of the new table by using lua_setglobal which POPS the top element from the stack (must be a table element), while associating the identifier with it.
Stack is now again empty.
How To Integrate Lua With Chrome
If at first the table did already exists, I make sure to balance the stack again properly in the else clause, by POPPING the found table object off the stack.
Either way the stack will look exactly as it did before entering the method.
How To Embed Lua In C++
This is the easiest way to ensure proper stack use.
There can be times though when it’s fitting to leave a table object on top of the stack when performing multiple operations on the same table, instead of constantly PUSHING and POPPING it on and off the stack.
It’s critical to know exactly how each lua API function will treat the stack when it is called.
How many arguments and their types will it assume on the stack when called?
How many elements will be left on the stack when the function is done?
You will have to look this behavior up in the lua documentation, until you get familiar with it.
This ends part III of Embedding Lua in C# .Net
I hope you will find the post and the code snippets useful.