main.lua
print("Hello from main.lua")
app.c
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(int argc, char **argv)
{
int status;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "require");
lua_pushliteral(L, "main");
status = lua_pcall(L, 1, 0, 0);
if (status) {
fprintf(stderr, "Error: %s
", lua_tostring(L, -1));
return 1;
}
return 0;
}
Shell commands:
luajit -b main.lua main.o
gcc -O2 -Wall -Wl,-E -o app app.c main.o -Ixx -Lxx -lluajit-5.1 -lm -ldl
Replace -Ixx
and -Lxx
by the LuaJIT include and library directories. If you've installed it in /usr/local
(the default), then most GCC installations will find it without these two options.
The first command compiles the Lua source code to bytecode and embeds it into the object file main.o
.
The second command compiles and links the minimal C application code. Note that it links in the embedded bytecode, too. The -Wl,-E
is mandatory (on Linux) to export all symbols from the executable.
Now move the original main.lua away (to ensure it's really running the embedded bytecode and not the Lua source code file) and then run your app:
mv main.lua main.lua.orig
./app
# Output: Hello from main.lua
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…