2016-06-13 90 views
-1

我有一个Lua解释器,只要我在代码中发生语法错误,返回的错误信息就是attempted to call a string value,而不是有意义的错误消息。例如,如果我运行这个Lua代码:Lua语法错误的描述性错误信息

for a= 1,10 
    print(a) 
end 

而不是返回有意义'do' expected near 'print'和行号的它只会返回错误attempted to call a string value

我的C++代码如下:提前

void LuaInterpreter::run(std::string script) { 
    luaL_openlibs(m_mainState); 

    // Adds all functions for calling in lua code 
    addFunctions(m_mainState); 

    // Loading the script string into lua 
    luaL_loadstring(m_mainState, script.c_str()); 

    // Calls the script 
    int error =lua_pcall(m_mainState, 0, 0, 0); 
    if (error) { 
     std::cout << lua_tostring(m_mainState, -1) << std::endl; 
     lua_pop(m_mainState, 1); 
    } 
} 

谢谢!

回答

7

您的问题是luaL_loadstring无法加载字符串替换

luaL_loadstring(m_mainState, script.c_str()); 

// Calls the script 
int error =lua_pcall(m_mainState, 0, 0, 0); 

来解决这个问题,因为它不是有效的Lua代码。但是你永远不会去检查它的返回值来发现这一点。因此,你最终试图执行编译错误,它将它压入堆栈,就像它是一个有效的Lua函数一样。

使用此功能的正确方法如下:

auto error = luaL_loadstring(m_mainState, script.c_str()); 
if(error) 
{ 
    std::cout << lua_tostring(m_mainState, -1) << std::endl; 
    lua_pop(m_mainState, 1); 
    return; //Perhaps throw or something to signal an error? 
} 
1

我能够通过与代码

int error = luaL_dostring(m_mainState, script.c_str());