Reputation: 850
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?
Upvotes: 0
Views: 307
Reputation:
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:
zstring.c
to an object file (e.g. gcc -c -o zstring.o zstring.c
)Create a header file named zstring.h
:
#ifndef ZSTRING_H
#define ZSTRING_H
int luaopen_zstring(lua_State *L);
#endif
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;
}
zstring.o
object file linked (e.g. gcc -o myprogram main.c zstring.o
)Upvotes: 1