0

i have this code (zstring.c)

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

static int zst_strlen(lua_State *L)
{
    size_t len;
    len = strlen(lua_tostring(L, 1));
    lua_pushnumber(L, len);
    return 1;
}

int luaopen_zstring(lua_State *L) 
{
    lua_register(L,"zst_strlen", zst_strlen);
    return 0;
}

and this is my lua embedded

int main (){
    L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L, "test.lua");
    lua_close(L);
    return 0;
}

i do not want compile zstring.c to zstring.so object

i want zstring.c compile into my embedded lua then i can call zstring from test.lua and use it

how to do it?

1 Answer 1

1

You can accomplish this by including the zstring source file then calling luaopen_zstring after initializing Lua:

#include "zstring.c"

int main (){
    L = luaL_newstate();
    luaL_openlibs(L);
    lua_pushcfunction(L, luaopen_zstring);
    lua_call(L, 0, 0);
    luaL_dofile(L, "test.lua");
    lua_close(L);
    return 0;
}

It should be noted that even if you do not want to generate a shared library, you can still create an object file for zstring (by using the -c flag with gcc, for example). You can then link that object file with your main source.

The steps for doing this are roughly:

  1. Compile zstring.c to an object file (e.g. gcc -c -o zstring.o zstring.c)
  2. Create a header file named zstring.h:

    #ifndef ZSTRING_H
    #define ZSTRING_H
    int luaopen_zstring(lua_State *L);
    #endif
    
  3. Include the header in your main source file:

    #include "zstring.h"
    
    int main (){
        L = luaL_newstate();
        luaL_openlibs(L);
        lua_pushcfunction(L, luaopen_zstring);
        lua_call(L, 0, 0);
        luaL_dofile(L, "test.lua");
        lua_close(L);
        return 0;
    }
    
  4. Compile the main file with the zstring.o object file linked (e.g. gcc -o myprogram main.c zstring.o)
Sign up to request clarification or add additional context in comments.

1 Comment

Do not call luaopen_* functions directly, call them through lua. While it may work (and certainly will for this luaopen_zstring function) it is better practice to always call them the normal way. The canonical way to do this is to edit the linit.c file included in the lua sources to add the desired modules to the list that luaL_openlibs loads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.