Passing Lua Script from C++ to Lua



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.

Example

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 !    /////////////////////////////////////////////    lua_close(L);    printf( "Press enter to exit..." );    getchar();    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.

Example

Consider the code shown below as −

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

Output

1 2 3 4 5


Updated on: 2021-07-19T12:01:48+05:30

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close