Embedded Lua-Script into C

This weekend, I played around a bit with Lua and C. My aim was to understand the Lua basics, embed the script engine into C and be able to even call a C function from Lua.

Lua Logo

With Google and a lot of documentation spread around the web this was a fairly easy task. The result are 2 short files. First file is the C-code main.c which initializes Lua, registers the C-function which will be later called by Lua and then executes the Lua-script. The Lua-script itself just does some prints, calls the C-function and prints the return-value.

I think that the files are nearly self-explaining, so I did not blow up the short files with big comments – if you need help with the Lua-functions, please have a look at the Lua 5.1 Reference Manual.

main.c:

#include <stdlib.h>
#include <stdio.h>

#include <lua5.1/lua.h>
#include <lua5.1/lualib.h>
#include <lua5.1/lauxlib.h>

static int c_hello (lua_State *L) {
    int i = 0;
    lua_Integer count = lua_tointeger(L, 1); // get first arg from stack

    putchar('\n');
    for (i = 0; i < count; i++) {
        printf("  C: %i. Hello from C\n", i+1);
    }   
    putchar('\n');

    lua_pushinteger(L, 1234); // push 1234 to return-stack
    return 1; // number of return-args
}

int main(void)
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    lua_pushcfunction(L, c_hello);
    lua_setglobal(L, "c_hello");

    printf("  C: Starting hello.lua from C\n\n");

    if (luaL_dofile(L, "hello.lua")) {
        printf("\n  C: Lua error: %s\n", lua_tostring(L, -1));
    } else {
        printf("\n  C: Lua code ran OK.\n");
    }   

    lua_close(L);

    return 0;
}

hello.lua:

local result = 0 

print("Lua: Hello from Lua")
print("Lua: Now I will call a c-function from Lua: c_hello(3)")
result = c_hello(3)
print("Lua: Result from c_hello: " .. result)
print("Lua: Bye from Lua")

My build-environment is Ubuntu 11.04 – if you also use it, you’ll need at least the package liblua5.1-0-dev. To build the code, enter the following line in your shell:

gcc -Wall -Wextra -o main main.c -llua5.1 -ldl -lm

Now you should be able to execute the main binary and get the following output:

  C: Starting hello.lua from C

Lua: Hello from Lua
Lua: Now I will call a c-function from Lua: c_hello(3)

  C: 1. Hello from C
  C: 2. Hello from C
  C: 3. Hello from C

Lua: Result from c_hello: 1234
Lua: Bye from Lua

  C: Lua code ran OK.

Good luck by playing around with Lua and C.

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.