* Source: [Lucas Klassmann blog](https://lucasklassmann.com/blog/2019-02-02-embedding-lua-in-c/) # Examples ```c #include #include #include int main(int argc, char ** argv) { lua_State *L = luaL_newstate(); luaL_openlibs(L); // Work with lua API lua_close(L); return 0; } ``` ```c #include #include #include int main(int argc, char ** argv) { lua_State *L = luaL_newstate(); luaL_openlibs(L); // Our Lua code, it simply prints a Hello, World message char * code = "print('Hello, World')"; // Here we load the string and use lua_pcall for run the code if (luaL_loadstring(L, code) == LUA_OK) { if (lua_pcall(L, 0, 0, 0) == LUA_OK) { // If it was executed successfuly we // remove the code from the stack lua_pop(L, lua_gettop(L)); } } lua_close(L); return 0; } ``` (Note that Lucas' blog contains a typo: his code has a lower case `l` in `lua_gettop(L)` which doesn't compile.) # Makefile ```make all: a b %: %.c gcc -o $@ $< -I/usr/include/lua5.4 -llua5.4 ``` # dofile We can already execute lua files. ```c #include #include #include int main(int argc, char ** argv) { lua_State *L = luaL_newstate(); luaL_openlibs(L); // Work with lua API char * code = "dofile('hello.lua')"; // Here we load the string and use lua_pcall for run the code if (luaL_loadstring(L, code) == LUA_OK) { if (lua_pcall(L, 0, 0, 0) == LUA_OK) { // If it was executed successfuly we // remove the code from the stack lua_pop(L, lua_gettop(L)); } } lua_close(L); return 0; } ``` # Shared Library ```c // exl001.c #include #include #include #include typedef struct { lua_State* state; } MyLua; MyLua* create_my_lua() { MyLua* mylua = (MyLua*)malloc(sizeof(MyLua)); mylua->state = luaL_newstate(); luaL_openlibs(mylua->state); return mylua; } void destroy_my_lua(MyLua* mylua) { lua_close(mylua->state); free(mylua); } static void test1(MyLua* mylua); void test() { MyLua *mylua = create_my_lua(); test1(mylua); destroy_my_lua(mylua); } static void test1(MyLua* mylua) { char * code = "dofile('hello.lua')"; lua_State* L = mylua->state; // Here we load the string and use lua_pcall for run the code if (luaL_loadstring(L, code) == LUA_OK) { if (lua_pcall(L, 0, 0, 0) == LUA_OK) { // If it was executed successfuly we // remove the code from the stack lua_pop(L, lua_gettop(L)); } } } ``` ```lua // hello.lua print("Hello, World! Woohoo!") ``` ```py import ctypes lib = ctypes.cdll.LoadLibrary("./exl001.so") test = lib.test test() ``` ```make all: exl001.so exl001.so: exl001.c gcc -I /usr/include/lua5.4 -o $@ $< -shared -llua5.4 ```