[英]C++ not catching lua exceptions
我有一個使用luabind綁定到Lua的C ++程序。 我目前正在測試lua和luabind必須提供的錯誤處理方法,以幫助調試后續的lua腳本。 目的是在出現語法錯誤和編程錯誤時讓luabind或lua引發異常,以便我可以調試和更正它們。
現在,問題在於下面的腳本只是停止執行,而沒有引發任何錯誤消息或異常,因此在較大的程序中,我什至不知道問題出在哪里,甚至根本就沒有問題。
以下是相關片段:
Lua:(start.lua)
--complete file shown, this is meant to test the error handling of the C++ program
print("This is valid")
print(1234)
bad_function()
a = "meow"
b = 7
c = a + b
C ++:
Engine *callbackEngine;
int theCallback(lua_State *L) //This is so I can use my own function as an
//exception handler, pcall_log()
{
return callbackEngine->pcall_log(L);
}
void Engine::Run()
{
luabind::set_pcall_callback(&theCallback); //my own callback function,
//redirects to
//pcall_log() below
try {
luaL_dofile(L, "scripts/start.lua");
}
catch(luabind::error &sError) { //This never gets executed, noted by breakpoints
theCallback(L);
}
//etc...code not shown
int Engine::pcall_log(lua_State *L)
{
lua_Debug d;
lua_getstack( L,1,&d);
lua_getinfo( L, "Sln", &d);
lua_pop(L, 1);
stringstream ss;
ss.clear();
ss.str("");
ss << d.short_src;
ss << ": ";
ss << d.currentline;
ss << ": ";
if ( d.name != 0)
{
ss << d.namewhat;
ss << " ";
ss << d.name;
ss << ") ";
}
ss << lua_tostring(L, -1);
logger->log(ss.str().c_str(),ELL_ERROR);
return 1;
}
這是運行時的輸出:
This is valid
1234
該腳本停止運行,而不是引發我所預期的異常。 有沒有一種方法可以控制lua何時引發異常或其他方法來處理錯誤? 我具有日志記錄功能設置來生成調試信息,但是斷點顯示上面的catch語句未得到執行。
謝謝!
luaL_dofile()
不屬於Luabind,所以我不希望它有任何Luabind異常。 當Luabind本身從Lua調用某些東西(使用pcall()
)時,將使用/傳遞您設置的處理程序。 luaL_dofile()
是基本Lua代碼的一部分(L后綴將其標記為庫包裝以簡化調用)和普通C,因此您必須自己進行錯誤處理(老實說,Lua / Luabind從未使用過異常)通話后。
未經測試,但是下面的代碼應該可以完成您期望的代碼:
if(!luaL_doFile(L, "scripts/start.lua"))
theCallback(L);
如果要通過Luabind加載Lua腳本,則不能使用luaL_dofile
或其他常規Lua函數來執行此操作。 您必須使用Luabind函數。 這樣看起來像這樣:
namespace lb = luabind;
int luaError = luaL_loadfile(pLuaState, "scripts/start.lua");
//Check for errors
lb::object compiledScript(lb::from_stack(pLuaState, -1));
lb::call_function<void>(compiledScript); //Call the script.
lua_pop(pLuaState, 1); //Remove the script from the stack. It's stored in our luabind::object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.