本文介绍了lua5.2 的错误:检测到多个 Lua 虚拟机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近在用5.2学习,想试试这个:

I use 5.2 for learning recently, what I want to try like this:

第一步,为lua构建一个c模块:

Step 1, build a c module for lua:

#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)"

I compile and link it with liblua.a, and I'm sure it works well in lua script like "require("tool") tool.add(1, 2)"

第 2 步,我编写了另一个 C 程序,它希望像这样在第 1 步中需要我的 c 模块:

Step 2, I write another C program that wants to require my c module in step 1 like this:

#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
");
        return 2;
    }
    lua_pushstring(L, "tool");
    if (lua_pcall(L, 1, 1, 0) != LUA_OK) {
        printf("require_fail=%s
", 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);
    return 0;
}

我也编译 &与 liblua.a 链接,但运行时出现错误:require_fail=检测到多个 Lua 虚拟机"

I also compile & link with liblua.a, but error occurs when I run it:"require_fail=multiple Lua VMs detected"

有人的博客说在lua5.2中,你应该动态链接c模块和c宿主程序,而不是静态链接.

Someone's blog said that in lua5.2, you should link c module and c host program both dynamicly, but not staticly.

有没有人有同样的问题,或者我的代码有什么问题,谢谢.

is there someone that has the same problem, or is there somehing wrong in my code, thanks.

注意:

问题已通过-Wl,-E编译主程序解决,非常感谢大家的帮助^^.

the problem has been solved by compile main program with -Wl,-E, thanks a lot for all your help ^^.

推荐答案

当您从 liblua.a 创建一个 .so 时,不要将它链接到您的 C 模块.例如,请参阅我的 Lua 库页面:http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ .您可以将 liblua.a 静态链接到主程序中,但您必须在链接时通过添加 -Wl,-E 来导出其符号.这就是 Linux 中 Lua 解释器的构建方式.

Don't link your C module with liblua.a when you create a .so from it. For examples, see my page of Lua libraries: http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/ . You can link liblua.a statically into your main program but you have to export its symbols by adding -Wl,-E at link time. That's how the Lua interpreter is built in Linux.

这篇关于lua5.2 的错误:检测到多个 Lua 虚拟机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 23:12