How to compile embedded Lua code in C?

LuaServer Side ProgrammingProgramming

We know that Lua does a great job when it comes to being a simple language and an embedded language. Lua works even better with C, because of the different libraries that provide a great amount of support for it.

In order to compile embedded Lua in C, we need to first write a Lua program followed by a C program that will invoke the Lua program function, and then we will compile the C program.

Consider the program shown below as the Lua program −

print("--I am using Lua from within C--")

It should be noted that the above Lua script should be saved as Script.Lua as we will make use of the name in the C code shown below. The above Lua script will be called in a C program.


Consider the code shown below −

#include <stdlib.h>
#include <stdio.h>
/* Include the Lua API header files. */
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
int main(void) {
   static const luaL_reg lualibs[] =
   { "base", luaopen_base },
   { NULL, NULL }
   { NULL,
   /* A function to open up all the Lua libraries you declared above. */ static void openlualibs(lua_State *l) {
   const luaL_reg *lib;
      for (lib = lualibs; lib->func != NULL; lib++) {
         lua_settop(l, 0);
   /* Declare a Lua State, open the Lua State and load the libraries (see above). */
   lua_State *l;
   l = lua_open();
   printf("This line in directly from C\n\n");
   lua_dofile(l, "script.lua");
   printf("\nBack to C again\n\n");
   /* Remember to destroy the Lua State */
   return 0;

Now we are done with the code; we just need to compile the C program shown above. For that, we can run the following command −

cc -o embed embed.c \
   -I/usr/local/include \
   -L/usr/local/lib \
   -llua -llualib

It should be noted that the name embed.c is the name of the C file shown above.

Also, the command shown above works only in case you are using a Linux machine.

To compile the code on Windows, we need to do the following steps −

  • Create a new project.
  • Add the embed.c file.
  • Add the 2 Lua libraries (*.lib) - Standard library and the Core library.
  • Add the locations of the Lua include files to the project options ("Directories tab").
  • You may also have to add the locations of the library files - the same way as above.
  • Compile and Build - that's it.


This line in directly from C
--I am using Lua from within C--
Back to C again
Updated on 20-Jul-2021 14:20:30