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\n", 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 include directories and LuaJIT libraries. If you installed it in /usr/local (by default), then most GCC installations will find it without these two options.
The first command compiles the Lua source code into bytecode and inserts it into the main.o object file.
The second command compiles and binds the minimum application code C. Note that it is also linked in the embedded bytecode. -Wl,-E is required (on Linux) to export all characters from an executable file.
Now move the main.lua source file (to make sure that it really runs the embedded bytecode, not the Lua source file), and then run the application:
mv main.lua main.lua.orig ./app
Mike pall
source share