Calling Lua from C
- Lua can be called from C
- The usual steps are:
- Start a new Lua state
- Open any desired Lua standard libraries
- Push a function and parameters onto the "Stack"
- Execute the function
- Pop results from the stack
- close the Lua state
An example of calling Lua from C
#include <stdio.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" int main (void) { char buff[256]; int error; lua_State *L = luaL_newstate(); /* opens Lua */ luaL_openlibs(L); /* opens the standard libraries */ while (fgets(buff, sizeof(buff), stdin) != NULL) { error = luaL_loadstring(L, buff) || lua_pcall(L, 0, 0, 0); if (error) { fprintf(stderr, "%s\n", lua_tostring(L, -1)); lua_pop(L, 1); /* pop error message from the stack */ } } lua_close(L); return 0; }
- To make the above code run the following steps are needed
- Download an Eclipse C programming IDE
- Install a C compiler on Windows it is easiest to use Minimalist GNU for Windows (mingw)
- Configure Eclipse so that it uses an installed C compiler (i.e. mingw gcc)
- Create a project
- Configure the project so that it uses the libLua.a library
- By setting project Properties/C C++ General/Paths and Symbols/Library Paths/Add
- Add the liblua.a library in Paths and Symbols/library add it as lua (remove lib and a)
- Configure the project with the correct C header files by copying and pasting them
- Or by specifying the path to them in Paths and Symbols
- Create the source code and build it
- Run the project