c++ - Lua语法错误的描述性错误消息

标签 c++ error-handling lua

我有一个Lua解释器,每当我在代码中出现语法错误时,返回的错误消息就是attempted to call a string value,而不是有意义的错误消息。例如,如果我运行以下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);
    }
}

提前致谢!

最佳答案

您的问题是luaL_loadstring无法加载字符串,因为它不是有效的Lua代码。但是,您不必费心检查它的返回值就可以找到答案。因此,您最终将试图执行 push 堆栈的编译错误,就像它是有效的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?
}

关于c++ - Lua语法错误的描述性错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781098/

相关文章:

c++ - 在模板容器中存储元素

error-handling - 用户输入为空时应该抛出什么异常?

java - 如何删除数组中的指定字符并将元素复制到另一个数组

卢阿 : Storing values in string array

c++ - 具有不同指向成员指针的参数的非类型模板参数的特化是否保证是唯一的特化?

c++ - wxWidgets构建成功后下一步做什么: Visual Studio 2010

C++ Lua(对象表的表)

performance - 在我的速度测试中,Lua 表哈希索引比数组索引更快。为什么?

c++ - 如何在没有对象的情况下执行槽函数?

PHP OO - 我应该如何处理多个类中的软错误?