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

Windows 10 x64,MSVC 2017,LuaJIT 2.0.5。

我搜了一下网络,但没有找到解决方案。

基本上我正在尝试按照这个手册的步骤进行操作,除了我必须在Lua包含之后放置#include<LuaBridge.h>,否则会出现错误,说LuaBridge应该在Lua包含之后使用。

但是,我遇到了以下错误:“PANIC:调用Lua API时的无保护错误(尝试调用一个nil值)”。

我不知道为什么。如果您需要更多信息,请告诉我。

#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 << "这里是我们的数字:" << answer << endl;
    system("pause");
    return 0;
}

script.lua:

testString = "LuaBridge工作了!"
number = 42
点赞
用户9383219
用户9383219

这个教程中的代码是有问题的。因为 luaL_dofileluaL_openlibs 没有将一个函数推到堆栈中, 所以 lua_pcall 没有函数可以调用,尝试调用 nil 并返回错误码 2 (宏值为 LUA_ERRRUN)。

我通过改变这个不正确的代码并使用 g++ 进行编译进行了验证。出于某种原因(也许是因为它正在使用 Lua 5.3),我没有得到PANIC错误:

#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; // 打印 lua_pcall 的返回值。这将打印 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 头文件!

2018-11-02 22:06:27