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()
        {
#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, 0, 1, errFunc);
            if (error != 0)
                luaEnv.ThrowExceptionFromError(oldTop);
            TResult ret;
            try
            {
                translator.Get(L, -1, out ret);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                LuaAPI.lua_settop(L, oldTop);
            }
            return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
            }
#endif
        }

    }

}

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

你可能感兴趣的:(Lua学习)