c#与lua交互里,错误处理

如果是c#代码出错了

[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_down(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
translator.PushUnityEngineVector3(L, UnityEngine.Vector3.down);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}

  会在所有导出的方法里,增加try  catch,然后把错再抛到lua里。

如果是lua代码出错了

[MonoPInvokeCallback(typeof(LuaCSFunction))]
        internal static int Panic(RealStatePtr L)
        {
            string reason = String.Format("unprotected error in call to Lua API ({0})", LuaAPI.lua_tostring(L, -1));
            throw new LuaException(reason);
        }

  

       public void ThrowExceptionFromError(int oldTop)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnvLock)
            {
#endif
                object err = translator.GetObject(L, -1);
                LuaAPI.lua_settop(L, oldTop);

                // A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
                Exception ex = err as Exception;
                if (ex != null) throw ex;

                // A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
                if (err == null) err = "Unknown Lua Error";
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
				    toLuaError toLua = LuaVM.Instance.luaEnv.Global.GetInPath<toLuaError>("reportError");
				    toLua(err.ToString());
#endif
            throw new LuaException(err.ToString());
#if THREAD_SAFE || HOTFIX_ENABLE
            }
#endif
        }

  会同时抛出c#的exception,这样c#的栈才能正确处理

posted on 2019-04-18 17:33  marcher  阅读(486)  评论(0编辑  收藏  举报

导航