简体   繁体   中英

Binding LuaJIT to C++ with LuaBridge results in “PANIC: unprotected error”

Windows 10 x64, MSVC 2017, LuaJIT 2.0.5.

I searched the web, but answers didn't help.

Basically I'm trying to follow this manual , except that I had to place #include <LuaBridge.h> after Lua includes, because otherwise it doesn't work saying that the LuaBridge should go after Lua includes.

Hovewher, I get following error: PANIC: unprotected error in call to Lua API (attempt to call a nil value) .

I have no idea why. If you need more info - just say what.

#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

The code in the tutorial is faulty. lua_pcall has nothing to call because luaL_dofile and luaL_openlibs don't push a function onto the stack, so it tries to call nil and returns 2 (the value of the macro LUA_ERRRUN ).

I verified this by changing the code from the tutorial thus and compiling with g++. I didn't get a PANIC error, for whatever reason; maybe because it was using 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;
}

As you noticed, the code is also faulty because the Lua headers have to be included before the LuaBridge header!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM