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 sin
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:
$ echo "x=1" > l1.lua
$ echo "y=2" > l2.lua
$ echo "print(x, y)" > l3.lua
$ luac -o run.luac l1.lua l2.lua l3.lua
$ lua run.luac
1 2
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 using lua_call
to 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:
-- http://lua-users.org/wiki/LuaCompilerInLua
-- compile the input file(s) passed as arguments and output them combined to stdout
local chunk = {}
for _, file in ipairs(arg) do
chunk[#chunk + 1] = assert(loadfile(file))
end
if #chunk == 1 then
chunk = chunk[1]
else
-- combine multiple input files into a single chunk
for i, func in ipairs(chunk) do
chunk[i] = ("loadstring%q(...);"):format(string.dump(func))
end
chunk = assert(loadstring(table.concat(chunk)))
end
io.write(string.dump(chunk))
For the previous sample, you can use it as follows:
$ luajit combine.lua l1.lua l2.lua l3.lua > out.ljc
$ luajit out.ljc
1 2