1. 程式人生 > >LUA是怎麼樣呼叫C++的函式的

LUA是怎麼樣呼叫C++的函式的

考慮下面一個功能,一個bug收集庫是c++實現的,現在當lua端出錯的時候,將bug日誌收集起來的功能:

void BuglyLuaAgent::registerLuaExceptionHandler(cocos2d::LuaEngine * engine) {
	lua_State *L = engine->getLuaStack()->getLuaState();

	lua_register(L, "buglyReportLuaException", BuglyLuaAgent::reportLuaException);
	lua_register(L, "buglySetUserId", BuglyLuaAgent::setUserId);
	lua_register(L, "buglySetTag", BuglyLuaAgent::setTag);
	lua_register(L, "buglyAddUserValue", BuglyLuaAgent::addUserValue);
	lua_register(L, "buglyRemoveUserValue", BuglyLuaAgent::removeUserValue);
	lua_register(L, "buglyLog", BuglyLuaAgent::printLog);

}

通過lua_register函式將c++方法註冊過來,對lua來說成為全域性函式。
local logfile = cc.FileUtils:getInstance():getWritablePath() .. "log.log"
function __G__TRACKBACK__( msg )
	--崩潰收集
	if buglyReportLuaException then
		local message = msg
		if gt.playerData and gt.playerData.uid then
			buglyAddUserValue("resVersion", tostring(cc.exports.gt.resVersion) or "")
			buglySetUserId(tostring(gt.playerData.uid))
		end
		buglyReportLuaException(tostring(message), debug.traceback())
	end
	
	--除錯模式顯示異常
	if gt.isDebugPackage then
		local logInfo = io.readfile(logfile)
		local logTab = string.split(logInfo, "\n")
		local ret = table.concat(logTab, "\n", #logTab > 100 and (#logTab - 100 ) or 1)
        require("app/views/ErrorTips"):create(ret .. "\n" .. "LUA ERROR: " .. tostring(msg) .. "\n" .. debug.traceback(), true)		
    end
	
    gt.log("LUA ERROR: " .. tostring(msg) .. "\n")
    gt.log(debug.traceback())
 end

xpcall(main, __G__TRACKBACK__)
通過xpall 來實現,當出錯的時候,就把日誌記錄下來。