我最近使用5.2进行学习,我想尝试这样做:
步骤1,为lua构建一个c模块:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
static int add(lua_State *L) {
int x = luaL_checkint(L, -2);
int y = luaL_checkint(L, -1);
lua_pushinteger(L, x + y);
return 1;
}
static const struct luaL_Reg reg_lib[] = {
{"add", add}
};
int luaopen_tool(lua_State *L) {
luaL_newlib(L, reg_lib);
lua_setglobal(L, "tool");
return 0;
}
我用liblua.a编译并链接它,我确信它在lua脚本中运行良好,例如“require(”tool“)tool.add(1,2)”
第2步,我写了另一个想要在步骤1中要求我的c模块的C程序,如下所示:
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include <stdlib.h>
int main(int argc, char* const argv[]) {
lua_State *L = luaL_newstate();
luaL_requiref(L, "base", luaopen_base, 1);
luaL_requiref(L, "package", luaopen_package, 1);
lua_getglobal(L, "require");
if (!lua_isfunction(L, -1)) {
printf("require not found\n");
return 2;
}
lua_pushstring(L, "tool");
if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
printf("require_fail=%s\n", lua_tostring(L, -1));
return 3;
}
lua_getfield(L, -1, "add");
lua_pushinteger(L, 2);
lua_pushinteger(L, 3);
lua_pcall(L, 2, 1, 0);
int n = luaL_checkint(L, -1);
printf("n=%d\n", n);
return 0;
}
我也编译&amp;链接liblua.a,但运行时出错: “require_fail =检测到多个Lua VM”
某人的博客说,在lua5.2中,你应该动态地链接c模块和c主机程序,但不能静态地链接。
是否有人遇到同样的问题,或者我的代码中存在错误,谢谢。
注意:
通过使用-Wl,-E编译主程序解决了这个问题,非常感谢你的帮助^^。
答案 0 :(得分:5)
从中创建.so时,不要将C模块与liblua.a链接。有关示例,请参阅我的Lua库页面:http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/。您可以将liblua.a静态链接到主程序,但必须通过在链接时添加-Wl,-E
来导出其符号。这就是Lua解释器在Linux中的构建方式。