使用LuaBridge将LuaJIT绑定到C ++会导致“ PANIC:未受保护的错误”

时间:2018-11-02 03:31:08

标签: c++ lua luajit luabridge

Windows 10 x64,MSVC 2017,LuaJIT 2.0.5。

我在网上搜索,但答案无济于事。

基本上,我要遵循#21182,除了我必须将#include <LuaBridge.h>放在Lua包括之后,因为否则,说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

1 个答案:

答案 0 :(得分:0)

教程中的代码错误。 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;
}

您注意到,该代码也是错误的,因为必须在LuaBridge头之前包含Lua头!