2016-06-13 57 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());