I’ve embedded lua together with a bytecode chunk into a project written in C.
Now when I extend my lua code base by adding .lua files, is there a way to keep this code in a single bytecode chunk?
(I know how to load multiple bytecode chunks. But making it load a single chunk and then forgetting about the glue code would just seem comfortable.)
I tried to use textual inclusion, but it seems there’s no keyword for this in Lua.
“Require” and “dofile” look at the files at run time, so the resulting bytecode after running “lua -b …” won’t include the code of those files.
And there’s no way for combining bytecode files either, is there? I mean so that, when creating a bytecode file, the “require” command would add the code of all those files into one bytecode file.
PS: Michal Kottman’s answer works for Lua, which is what I asked for. I thought Lua and LuaJIT would work the same way. They don’t. To combine multiple .lua files to one LuaJIT bytecode file, should one
- use “LuaJIT -b” (seems not to work)
- compile Lua’s luac.c with LuaJIT sources
- emulate luac.c with lua commands (without C API) ?
You can combine multiple files into a single file using luac. When run, all the chunks from the source files are executed in the order they were added to the compiled file:
You can load this file into Lua from C using
luaL_loadfile, which places a function on the top of the stack if it loaded succesfully. Then you can just run this function usinglua_callto run all the combined compiled files.Note that you can embed the contents of the compiled file as a string into your project, no need to keep it in external file.
Update for LuaJIT 2
As you have found, you can use the Lua Compiler in Lua to get a combined file which can be loaded as previously noted. This is a simplified version, which outputs to stdout:
For the previous sample, you can use it as follows: