基本用法如下:
- 使用luajit生成头文件
#include
源文件中将引用其符号的标头
- 根据您的用例,将源代码编译为 lua 的可运行可执行文件或共享二进制模块。
这是一个最小的例子来说明:
测试.lua
return
{
fooprint = function (s) return print("from foo: "..s) end,
barprint = function (s) return print("from bar: "..s) end
}
测试.h
// luajit -b test.lua test.h
#define luaJIT_BC_test_SIZE 155
static const char luaJIT_BC_test[] = {
27,76,74,1,2,44,0,1,4,0,2,0,5,52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,
102,114,111,109,32,102,111,111,58,32,10,112,114,105,110,116,44,0,1,4,0,2,0,5,
52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,102,114,111,109,32,98,97,114,
58,32,10,112,114,105,110,116,58,3,0,2,0,5,0,7,51,0,1,0,49,1,0,0,58,1,2,0,49,1,
3,0,58,1,4,0,48,0,0,128,72,0,2,0,13,98,97,114,112,114,105,110,116,0,13,102,
111,111,112,114,105,110,116,1,0,0,0,0
};
运行测试.cpp
// g++ -Wall -pedantic -g runtest.cpp -o runtest.exe -llua51
#include <stdio.h>
#include <assert.h>
#include "lua.hpp"
#include "test.h"
static const char *runtest =
"test = require 'test'\n"
"test.fooprint('it works!')\n"
"test.barprint('it works!')\n";
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
// package, preload, luaJIT_BC_test
bool err = luaL_loadbuffer(L, luaJIT_BC_test, luaJIT_BC_test_SIZE, NULL);
assert(!err);
// package.preload.test = luaJIT_BC_test
lua_setfield(L, -2, "test");
// check that 'test' lib is now available; run the embedded test script
lua_settop(L, 0);
err = luaL_dostring(L, runtest);
assert(!err);
lua_close(L);
}
这很简单。此示例获取字节码并将其放入package.preload
该程序的 lua 环境的表中。然后其他 lua 脚本可以通过require 'test'
. 嵌入的 lua 源runtest
正是这样做并输出:
from foo: it works!
from bar: it works!