Sam Nolan
Sam Nolan

Reputation: 94

Descriptive Error Messages for Lua Syntax Errors

I have a Lua interpreter that whenever I make a syntax error in my code, the error message returned is simply attempted to call a string value, instead of a meaningful error message. For example if I run this lua code:

for a= 1,10
   print(a)
end

Instead of returning a meaningful 'do' expected near 'print' and a line number it will just return the error attempted to call a string value.

My C++ code is the following:

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);
    }
}

Thanks in advance!

Upvotes: 0

Views: 946

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 474486

Your problem is that luaL_loadstring fails to load the string, since it is not valid Lua code. But you never bother to check its return value to find this out. And therefore, you wind up trying to execute the compile error that it pushed onto the stack as though it were a valid Lua function.

The correct way to use this function is as follows:

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?
}

Upvotes: 7

Sam Nolan
Sam Nolan

Reputation: 94

I was able to fix the issue by replacing

luaL_loadstring(m_mainState, script.c_str());

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

with the code

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

Upvotes: 1

Related Questions