Embedding Lua script into a C program

Embedding Lua script into a C program

Just for curiosity I wanted to try embedding a Lua script into a little C program and surprisingly it resulted in a pretty quick and easy task.

Lua provides C API and everything is done within a few lines of code.

Let’s assume that our Lua script just prints “hello world” once it is executed and contains also a function to be called later.

Save a file as “hello.lua” and fill in with:

print("Hello world!");

function foo()
 print("Hi I am the foo function!");
end

Then create the C program that will run Lua ans save it as “embed_hello.c” with the following content:

#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* lua interpreter */
lua_State* l;

int main () {
  int dofile;

  /* initialize lua */
  l = lua_open();

  /* load lua libraries */
  luaL_openlibs(l);

  /* run the hello.lua script */
  dofile = luaL_dofile(l, "hello.lua");

  if (dofile == 0) {
    /* call foo */
    lua_getglobal(l,"foo");
    lua_call(l,0,0);
  }
  else {
    printf("Error, unable to run hello.lua\n");
  }

  /* cleanup Lua */
  lua_close(l);

  return 0;
}

Compile:

$ gcc -o embed_hello -Wall -L/opt/local/lib -I/opt/local/include \
-llua embed_hello.c

That’s all. This example works for OS X and Lua installed from macports. For other OSs and configurations just adapt the gcc command.

Execute it

$ ./embed_hello
Hello world!
Hi I am the foo function!


References:

1 thought on “Embedding Lua script into a C program

  1. Why you uses “-L/opt/local/lib” in compilation? this is only for mac OS? how i compile this in Linux? can you tell me what each parameter means?

    tks!

Leave a Comment