xlua中自定义lua文件加载的一种方式

此种方法来自LoxodonFramework,这里只做记录
定义一个LoaderBase类,做一个到CustomLoader的隐式类型转换

public abstract class LoaderBase
{
    protected abstract byte[] Load(ref string fileName);
    
    /// <summary>
    /// 隐式类型转换,将LoaderBase转换为CustomLoader的byte[]
    /// </summary>
    /// <param name="loader"></param>
    /// <returns></returns>
    public static implicit operator LuaEnv.CustomLoader(LoaderBase loader)
    {
        return loader.Load;
    }
}

再让一个PathLoaderBase类继承,做进一步路径封装

public abstract class PathLoaderBase : LoaderBase, IDisposable
{
    /// <summary>
    /// 前缀
    /// </summary>
    protected string prefix = "";
    
    /// <summary>
    /// 后缀
    /// </summary>
    protected string suffix = ".lua.txt";

    public PathLoaderBase(string prefix, string suffix)
    {
        this.prefix = prefix;
        if (!string.IsNullOrEmpty(this.prefix))
        {
            this.prefix = this.prefix.Replace(@"\", "/");
        }
        if (!this.prefix.EndsWith("/"))
        {
            this.prefix += "/";
        }
        this.suffix = suffix;
    }
    
    /// <summary>
    /// 得到文件路径
    /// </summary>
    /// <param name="className">文件名</param>
    /// <returns></returns>
    protected virtual string GetFullName(string className)
    {
        return string.Format($"{prefix}{className.Replace(".", "/")}{suffix}");
    }

    protected virtual void Dispose(bool disposing)
    {
        
    }

    ~PathLoaderBase()
    {
        Dispose(false);
    }
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

最后,来个FileLoader类,继承PathLoaderBase,具体重写Load方法

public class FileLoader : PathLoaderBase
{
    public FileLoader(string prefix, string suffix) : base(prefix, suffix)
    {
    }

    public FileLoader(string prefix) : this(prefix, ".lua.txt")
    {
        
    }
    
    /// <summary>
    /// 加载require的文件
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    protected override byte[] Load(ref string fileName)
    {
        string fullName = GetFullName(fileName);
        if (!FileUtil.Exists(fullName))
        {
            return null;
        }
        
        fileName = fullName;

        byte[] data = FileUtil.ReadAllBytes(fullName);
        if (!HasBOMFlag(data))
        {
            return data;
        }

        return data.Skip(3).ToArray(); //跳过BOM开头
    }
    
    /// <summary>
    /// 检查一个字节数组是否以字节顺序标记(Byte Order Mark, BOM)开头,
    /// BOM是一种用于指示文本文件编码方式的特殊字节序列,通常出现在文件的开头
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    protected bool HasBOMFlag(byte[] data)
    {
        if (data == null || data.Length < 3)
        {
            return false;
        }

        if (data[0] == 239 && data[1] == 187 && data[2] == 191)
        {
            return true;
        }

        return false;
    }
}
public static class FileUtil
{
    private static List<IZipAccessor> list = new List<IZipAccessor>();

        public static void Register(IZipAccessor zipAccessor)
        {
            if (list.Contains(zipAccessor))
                return;
            list.Add(zipAccessor);
            list.Sort((x, y) => y.Priority.CompareTo(x.Priority));
        }

        public static void Unregister(IZipAccessor zipAccessor)
        {
            if (!list.Contains(zipAccessor))
                return;
            list.Remove(zipAccessor);
        }

        public static string[] ReadAllLines(string path)
        {
            return ReadAllLines(path, Encoding.UTF8);

        }
        public static string[] ReadAllLines(string path, Encoding encoding)
        {
            if (!IsZipArchive(path))
                return File.ReadAllLines(path, encoding);

            string line;
            List<string> lines = new List<string>();
            using (var stream = OpenReadInZip(path))
            {
                using (StreamReader sr = new StreamReader(stream, encoding, true))
                {
                    while ((line = sr.ReadLine()) != null)
                        lines.Add(line);
                }
            }
            return lines.ToArray();
        }

        public static string ReadAllText(string path)
        {
            return ReadAllText(path, Encoding.UTF8);
        }

        public static string ReadAllText(string path, Encoding encoding)
        {
            if (!IsZipArchive(path))
                return File.ReadAllText(path, encoding);

            byte[] data = ReadAllBytes(path);
            if (!HasBOMFlag(data))
                return encoding.GetString(data);

            return encoding.GetString(data, 3, data.Length - 3);
        }
        
        /// <summary>
        /// 读取文件内容转换为字节数组
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static byte[] ReadAllBytes(string path)
        {
            if (!IsZipArchive(path))
                return File.ReadAllBytes(path);

            using (var stream = OpenReadInZip(path))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }

        public static Stream OpenRead(string path)
        {
            if (!IsZipArchive(path))
                return File.OpenRead(path);

            return OpenReadInZip(path);
        }

        public static bool Exists(string path)
        {
            if (!IsZipArchive(path))
                return File.Exists(path);

            return ExistsInZip(path);
        }

        private static Stream OpenReadInZip(string path)
        {
            for (int i = 0; i < list.Count; i++)
            {
                IZipAccessor zipAccessor = list[i];
                if (zipAccessor.Support(path))
                    return zipAccessor.OpenRead(path);
            }

#if UNITY_ANDROID
            if (path.IndexOf(".obb", StringComparison.OrdinalIgnoreCase) > 0 && log.IsWarnEnabled)
                log.Warn("Unable to read the content in the \".obb\" file, please click the link for help, and enable access to the OBB file. https://github.com/cocowolf/loxodon-framework/blob/master/docs/faq.md");
#endif

            throw new NotSupportedException(path);
        }

        private static bool ExistsInZip(string path)
        {
            for (int i = 0; i < list.Count; i++)
            {
                IZipAccessor zipAccessor = list[i];
                if (zipAccessor.Support(path))
                    return zipAccessor.Exists(path);
            }

            throw new NotSupportedException(path);
        }

        public static bool IsZipArchive(string path)
        {
            if (Regex.IsMatch(path, @"(jar:file:///)|(\.jar)|(\.apk)|(\.obb)|(\.zip)", RegexOptions.IgnoreCase))
                return true;
            return false;
        }

        static bool HasBOMFlag(byte[] data)
        {
            if (data == null || data.Length < 3)
                return false;

            if (data[0] == 239 && data[1] == 187 && data[2] == 191)
                return true;

            return false;
        }

        public interface IZipAccessor
        {
            int Priority { get; }

            bool Support(string path);

            Stream OpenRead(string path);

            bool Exists(string path);
        }
}

最后在LuaBehaviour类中写一个方法,做Lua的自定义加载

public class LuaBehaviour : MonoBehaviour
{
	...........
	/// <summary>
    /// 设置xlua的加载路径
    /// </summary>
    private void SetPackagePath()
    {
        //在Unity项目的“Assets”文件夹(或指定的Application.dataPath路径)及其所有子目录中,查找名为“LuaScripts”的目录,并返回一个包含这些目录路径的字符串数组
        foreach (string dir in Directory.GetDirectories(Application.dataPath,"LuaScripts", SearchOption.AllDirectories))
        {
            luaEnv.AddLoader(new FileLoader(dir, ".lua"));
            luaEnv.AddLoader(new FileLoader(dir, ".lua.txt"));
        }
    }
	..............
}

这样,Lua代码就可以require目录为“LuaScripts”下的所有Lua文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值