Lua is a scripting language with simple syntax and very fast execution time. It may be easily embedded in a variety of environments including C/C++ applications.
There are many general tutorials geared towards the general aspects of embedding Lua. This pair of examples is directed towards a specific application need in which multiple scripts may be run based on application events and information should be returned to the parent applications and/or other scripts for processing.
It was not easy for me to find examples which incorporated the following elements:
- cross platform including Windows
- full worked sample code, not just excerpts showing the use of functions
- reasonably detailed handling of edge cases including type errors and things like ‘nil’ as values
This is the first in a pair of essays which address, in order, how to embed Lua scripting in such an application and then how to pass data back and forth between the Lua and application environments. The second article expands to include pass data and function calls between Lua and c++. The source in the form of Visual Studio projects for both articles is available in a single repository at https://github.com/SoftwareSideRoads/embedluacplusplus
In order to keep things as simple as possible yet still maintain Lua as a separate library, we will:
- Create a basic solution and then C++ windows console application in Visual Studio 2022
- Create a static C/C++ library project in Visual Studio which will be the Lua library
- Create C and C++ applications which load a simple script from a string and run it.
- Add a reference to the Lua library from the applications
Tne C++ code can be found within the repository at basic embedding of Lua in C++. The corresponding example without C++ is available at basic embedding of lua in C. Because Lua is written in C, the level of power available to the parent application is basically the same whether the host application is C or C++.
Once the project structure is established, the minimum calls to run a Lua script within the parent application are quite simple:
- lua_openstring()
- lua_openlibs()
- lua_loadbuffer()
- lua_pcall()
- lua_close()
Without further connections between the application and scripting environment, there would not generally be much of a point to doing this as the same functional result could be obtained by simply executing a Lua interpreter on the script.
The followup article will add a project which demonstrates how to maintain state for a particular script between runs and how to pass data back to the application from the script.
Leave a Reply