天天看点

C#访问lua自定义loader

/*
 * 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.
*/

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using XLua;
using System;
using System.IO;

namespace Tutorial
{
    public class CSCallLua : MonoBehaviour
    {
        LuaEnv luaenv = null;
        public class DClass
        {
            public int f1;
            public int f2;
        }

        [CSharpCallLua]
        public delegate int FDelegate(int a, string b, out DClass c, ref int x, ref string y);

        void Start()
        {
            luaenv = new LuaEnv();
            //TextAsset luaScript = Resources.Load<TextAsset>("hello");
            //luaenv.DoString(luaScript.text);
            luaenv.AddLoader(SelfDefineLoader);
            luaenv.DoString("require 'hello'"); //使用requre 'xxxx'的方式,会触发自定义的loader
            FDelegate f = luaenv.Global.Get<FDelegate>("f");
            DClass d_ret;
            int x = 0;
            string y = string.Empty;
            int f_ret = f(100, "John", out d_ret, ref x, ref y);
        }

        /// <summary>
        /// 自定义的路径的加载器
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public byte[] SelfDefineLoader(ref string filepath)
        {
            filepath = Application.dataPath + "/XLua/Tutorial/CSharpCallLua/Resources/" + filepath + ".txt";
            if (File.Exists(filepath))
            {
                return File.ReadAllBytes(filepath);
            }
            else
            {
                return null;
            }
        }

        void OnDestroy()
        {
            luaenv.Dispose();
        }
    }
}

           

lua文件:

function f(a, b)
	print('a', a, 'b', b)
	return 1, {f1 = 1024}, 999, "hello,world"
end
           
C#访问lua自定义loader
C#访问lua自定义loader
C#访问lua自定义loader