【问题标题】:Binding LuaJIT to C++ with LuaBridge results in "PANIC: unprotected error"使用 LuaBridge 将 LuaJIT 绑定到 C++ 会导致“PANIC: unprotected error”
【发布时间】:2019-04-06 07:54:36
【问题描述】:

Windows 10 x64、MSVC 2017、LuaJIT 2.0.5。

我搜索了网络,但答案没有帮助。

基本上我正在尝试关注this manual,除了我必须在 Lua 包含之后放置 #include <LuaBridge.h>,否则说 LuaBridge 应该在 Lua 包含之后是行不通的。

但是,我收到以下错误:PANIC: unprotected error in call to Lua API (attempt to call a nil value)

我不知道为什么。如果您需要更多信息 - 请直接说出来。

#include "stdafx.h"
#include <iostream>
#include <lua.hpp>
#include <LuaBridge/LuaBridge.h>

using namespace luabridge;
using namespace std;

int main()
{
    lua_State* L = luaL_newstate();
    luaL_dofile(L, "script.lua");
    luaL_openlibs(L);
    lua_pcall(L, 0, 0, 0);
    LuaRef s = getGlobal(L, "testString");
    LuaRef n = getGlobal(L, "number");
    string luaString = s.cast<string>();
    int answer = n.cast<int>();
    cout << luaString << endl;
    cout << "And here's our number:" << answer << endl;
    system("pause");
    return 0;
}

script.lua:

testString = "LuaBridge works!"
number = 42

【问题讨论】:

  • 你的代码是什么样的?
  • 另外,你用的是luaL_loadfile还是luaL_dofile
  • 加了代码,我用的是luaL_dofile
  • 你所有的 .lua 文件是否和你的 c++ 源代码和头文件在同一个目录中?
  • lua_pcall(L, 0, 0, 0); 之前,您需要将一些东西压入堆栈(例如,您将要调用的函数)。你的 script.lua 什么都不返回,所以堆栈中没有任何内容。

标签: c++ lua luajit luabridge


【解决方案1】:

教程中的代码有问题。 lua_pcall 没有可调用的内容,因为 luaL_dofileluaL_openlibs 不会将函数压入堆栈,因此它会尝试调用 nil 并返回 2(宏 LUA_ERRRUN 的值)。

我通过更改教程中的代码并使用 g++ 编译来验证这一点。无论出于何种原因,我都没有收到 PANIC 错误;可能是因为它使用的是 Lua 5.3:

#include <iostream>
extern "C" {
# include "lua.h"
# include "lauxlib.h"
# include "lualib.h"
}
#include <LuaBridge/LuaBridge.h>

using namespace luabridge;
int main() {
    lua_State* L = luaL_newstate();
    luaL_dofile(L, "script.lua");
    std::cout << "type of value at top of stack: " << luaL_typename(L, -1) << std::endl;
    luaL_openlibs(L);
    std::cout << "type of value at top of stack: " << luaL_typename(L, -1) << std::endl;
    std::cout << "result of pcall: " << lua_pcall(L, 0, 0, 0) << std::endl; // Print return value of lua_pcall. This prints 2.
    LuaRef s = getGlobal(L, "testString");
    LuaRef n = getGlobal(L, "number");
    std::string luaString = s.cast<std::string>();
    int answer = n.cast<int>();
    std::cout << luaString << std::endl;
    std::cout << "And here's our number: " << answer << std::endl;
}

正如您所注意到的,代码也有问题,因为 Lua 头必须包含在 LuaBridge 头之前!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2018-09-04
    • 2015-10-25
    • 1970-01-01
    • 2013-11-29
    • 2018-08-11
    • 2013-10-30
    相关资源
    最近更新 更多