Embedding Lua in C

Bedimming lua in you C programs is can be done in few minutes. Many examples is in lua-users.org.

First thing to write is module and then compile everything with lua precompiled lib.

int module_register(lua_State*);
void module_print(lua_State*);
int module_getone(lua_State*);

int module_gc(lua_State*);
int module_tostring(lua_State*);

static const luaL_reg module_methods[] =
{
    //{,(void *)},
    {"print",   (void *)module_print},
    {"getone",  (void *)module_getone},
    {0,         0}
};

static const luaL_reg module_meta[] = 
{
    {"__gc",        (void *)module_gc},
    {"__tostring",  (void *)module_tostring},
    {0, 0}
};

to make printf("%s\n") available in lua

void module_print( lua_State *L)
{
    int argc = lua_gettop(L);
    int n;
    for (n=1; n <= argc; n++) printf("%s\n", lua_tostring(L, n));
}

next one function that have return value 1

int module_getone(lua_State *L)
{
    int x=1;
    lua_pushnumber(L, x);
    return 1;
}

and easy to compile if needed.

gcc -c module.c
gcc module.o main.c -o main -llua

Links

http://lua-users.org/wiki/SampleCode

Downloads

lua_embed.zip - 2KiB - http://archive.main.lv/files/writeup/embeding_lua_in_c/lua_embed.zip