Passing Lua script from C++ to Lua

LuaServer Side ProgrammingProgramming

The idea of passing Lua script from C++ to Lua includes the fact that we will have to load the libraries and header files as Lua is ANSI C, and if we are coding in C++, we will need to enclose the #includes in extern “C”.

The old and mostly used approach would be to load the libraries that Lua provides and then simply call the C++ function from Lua.

In order to load the script from C++ to Lua, we need to set up and shutdown the Lua interpreter and we can do that with the help of the following code.


Consider the code shown below as −

extern "C" {
   #include "lua.h"
   #include "lualib.h"
   #include "lauxlib.h"
int main(int argc, char *argv[]){
   lua_State* L;
   initialize Lua interpreter L = luaL_newstate();
   load Lua base libraries (print / math / etc) luaL_openlibs(L);
   We can use Lua here !
   printf( "Press enter to exit..." );
   return 0;

And after this we can simply make use of the LuaL_dostring(L, …) function that sends a string straight to the Lua interpreter, and it will be executed just as if that string was in a file that was executed with a dofile.


Consider the code shown below as −

luaL_dostring(L, "for x = 1, 5 do print(x) end");



Published on 19-Jul-2021 11:59:57