天天看點

XLua架構搭建——LuaFunction分部類擴充

Lua中函數在c#中的映射是LuaFunction,對函數的調用一般是用call來調用,但是官方認為這個效率上存在一定的GC,是以提供了Action和Func,其中Action是調用,沒有傳回值,而Func是有傳回值的。

在實際使用時發現少了一個函數,就是我調用的是無參函數,但是希望能拿到傳回值,官方的代碼裡并沒有相關函數,但是閱讀代碼可以發現,這是一個分部類,官方也鼓勵我們自己擴建相關函數,看官方代碼,依葫蘆畫瓢,增加一個相關的功能并不是太難,注釋LuaAPI的使用即可。

下面是實作的無參有傳回值的函數:

/*
 * Tencent is pleased to support the open source community by making xLua available.
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif

using System;
using System.Collections.Generic;

namespace XLua
{
    public partial class LuaFunction : LuaBase
    {

        public TResult Func<TResult>()
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            var L = luaEnv.L;
            var translator = luaEnv.translator;
            int oldTop = LuaAPI.lua_gettop(L);
            int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
            LuaAPI.lua_getref(L, luaReference);
            int error = LuaAPI.lua_pcall(L, , , errFunc);
            if (error != )
                luaEnv.ThrowExceptionFromError(oldTop);
            TResult ret;
            try
            {
                translator.Get(L, -, out ret);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                LuaAPI.lua_settop(L, oldTop);
            }
            return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
            }
#endif
        }

    }

}

           

QQ交流群:517539056,歡迎大家加入一起交流