In my application, I have all the Lua libraries exposed from the C backend. Now, I have a need to load a Lua module. The method for this seems to be :
lua_getglobal(L, "require");
lua_pushstring(L, libname);
lua_pcall(L, 1, 0, 0);
which will search the package.path
to find <libname>.lua
and load it.
Is it possible to build-in the Lua module into the C application (so that the module becomes part of the C application) ? so that I don't have to separately package the Lua module. Somehow I am not able to find any references or examples of this! :(
p.s. I am using LuaJIT-2.0.2
, and the library in question is SciLua/Time
(uses ffi
)
Yes.
luajit -b Module.lua Module_bc.c
will compile a module to bytecode and output a C array initializer containing that bytecode.
If you build with shared libraries enabled and export this array from the main executable, require
will find it (and will not need to look for Module.lua
.)
To test that it is working, set package.path = ""
before require
ing the module. If it still works, you know the preload is working and it is not just using the Module.lua
file from the current directory.
http://luajit.org/running.html
Other things to keep in mind:
io.open
), that file still needs to be present. For example some ffi modules try to open a C header file, to pass to ffi.cdef
Module_bc.c
in sync with Module.lua
, e.g. with a Makefile recipe, or you will see some confusing bugs!If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With