示例#1
0
 public void AddLoader(string _LuaScriptsPath = "/LuaScripts/")
 {
     //工作目录
     luaEnv.AddLoader(
         //项目内路径
         (ref string _fileName) => {
         string path = Application.dataPath + _LuaScriptsPath + _fileName;
         //Debug.Log(path);
         //path = path.Replace("/","\\");
         bool exist = File.Exists(path);
         Debug.Log(exist + ": " + path);
         if (!exist)
         {
             return(null);
         }
         //string context = File.ReadAllText(path, System.Text.Encoding.UTF8);
         //return System.Text.Encoding.UTF8.GetBytes(context);
         return(File.ReadAllBytes(path));
     }
         );
     luaEnv.AddLoader(
         //用户机器路径
         (ref string _fileName) => {
         string path = Application.persistentDataPath + _LuaScriptsPath;
         bool exist  = File.Exists(path + _fileName);
         if (!exist)
         {
             return(null);
         }
         //string context = File.ReadAllText(path, System.Text.Encoding.UTF8);
         //return System.Text.Encoding.UTF8.GetBytes(context);
         return(File.ReadAllBytes(path));
     }
         );
 }
示例#2
0
        private void init()
        {
            LuaEnv = new XLua.LuaEnv();


            LuaEnv.AddLoader(FileUtils.LuaLoader);
        }
示例#3
0
    /// <summary>
    /// 选择一个资源加载器
    ///
    /// 1. 如果可写目录下存在模块目录,则优先使用可写目录作为资源目录
    /// 2. 如果可写目录不存在模块目录,则两种情况:
    /// 2.1 如果处于编辑器模式,则使用assets目录
    /// 2.2 如果不处于编辑器模式,则使用streamingAssets目录
    /// </summary>
    void SelectModuleLoader()
    {
        var writeModuleDir = Path.Combine(Application.persistentDataPath, "modules", modName);

        if (Directory.Exists(writeModuleDir))
        {
            Debug.Log($"{writeModuleDir} exist, try to use writable dir");
            var modePathRoot = Application.persistentDataPath;
#if !UNITY_EDITOR
            if (IsStreamingAssetsPathModVersionNewer())
            {
                // 只读目录模块的cfg.json内的版本号比较新,这可能是由于刚安装了更加新版本的APP,自带的
                // 模块版本号比较新的缘故,因此使用只读目录,并删除老的可写目录(清理垃圾)
                Debug.Log("StreamingAssetsPath module version is newer, use StreamingAssetsPath instead of persistentDataPath");
                modePathRoot = Application.streamingAssetsPath;

                Debug.Log("Delete older persistentDataPath module content");
                // 删除老的可写目录模块内容
                Directory.Delete(writeModuleDir, true);
            }
#endif
            modePathRoot = Path.Combine(modePathRoot, "modules");
            AssetBundleLoader parentLoader = parent?.loader as AssetBundleLoader;
            loader = new AssetBundleLoader(modName, parentLoader, modePathRoot);
        }
        else
        {
#if UNITY_EDITOR
            Debug.Log($"{writeModuleDir} not exist, use readonly dir editor Assets directory");
            loader = new AssetsFolderLoader(modName);
#else
            Debug.Log($"{writeModuleDir} not exist, use readonly dir streamingAssetsPath directory");
            AssetBundleLoader parentLoader = parent?.loader as AssetBundleLoader;
            // 用的是StreamingAssetsPath,而不用Resources目录,原因参考下面的链接:
            // https://unity3d.com/learn/tutorials/topics/best-practices/resources-folder
            var modePathRoot = Path.Combine(Application.streamingAssetsPath, "modules");
            loader = new AssetBundleLoader(modName, parentLoader, modePathRoot);
#endif
        }

        // 把加载器增加到lua虚拟机中
        luaenv.customLoaders.Clear();
        luaenv.AddLoader((ref string filepath) =>
        {
            var patch = filepath;

            // 把形如 require 'a.b.c'替换成 require 'a/b/c'
            // 注意lua代码中,万万不能require('a.lua'),因为这样的话,路径名是a.lua,
            // 会被下面这行代码替换为:a/lua了,就加载失败
            patch = patch.Replace('.', '/');
            // 确保文件名字带有".lua"后缀,这样才能跟
            // 打包时的文件名对应,注意lua代码中,万万不能require('a.lua'),因为这样的话,路径名是a.lua,
            // 会被上面这行代码替换为:a/lua了,就加载失败
            filepath = patch + ".lua";

            // Debug.Log($"load lua file:{filepath}");
            return(loader.LoadTextAsset(filepath));
        });
    }
示例#4
0
 // Start is called before the first frame update
 void Start()
 {
     luaEnv = new XLua.LuaEnv();
     luaEnv.AddLoader((ref string filepath) =>
     {
         string path = PathDefines.luaDataPath + filepath + ".lua";
         return(File.ReadAllBytes(path));
     });
     luaEnv.DoString(GameMainLua.text, "GameMainLua");
 }
示例#5
0
    private void Start()
    {
        var env = new XLua.LuaEnv();

        env.AddLoader(CustomLoad);

        env.DoString("print('this is CustomLoader'");

        env.Dispose();
        env = null;
    }
示例#6
0
 // 创建Lua虚拟机
 private void CreateLuaEnv()
 {
     _luaEnv = new LuaEnv();
     if (_luaEnv != null)
     {
         _luaEnv.AddLoader(CustomLoader);
     }
     else
     {
         Debug.LogError("CreateLuaEnv _luaEnv is null.");
     }
 }
示例#7
0
    private XLua.LuaEnv CreateLuaEnv()
    {
        XLua.LuaEnv luaEnv = new XLua.LuaEnv();

        /*
         * luaEnv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);
         * luaEnv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
         * luaEnv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadLuaProfobuf);
         * luaEnv.AddBuildin("ffi", XLua.LuaDLL.Lua.LoadFFI);
         */
        luaEnv.AddLoader(this.LoadLuaScript);
        return(luaEnv);
    }
示例#8
0
        // second step
        public virtual void StartScript()
        {
            _luaenv = new XLua.LuaEnv();
            _luaenv.AddBuildin("cjson", Maria.Lua.BuildInInit.LoadCJson);
            _luaenv.AddBuildin("lpeg", Maria.Lua.BuildInInit.LoadLpeg);
            _luaenv.AddBuildin("sproto.core", Maria.Lua.BuildInInit.LoadSprotoCore);
            _luaenv.AddBuildin("ball", Maria.Lua.BuildInInit.LoadBall);
            _luaenv.AddLoader((ref string filepath) => {
                UnityEngine.Debug.LogFormat("LUA custom loader {0}", filepath);

                string[] xpaths = filepath.Split(new char[] { '.' });
                string path     = "xlua/src";
                int idx         = 0;
                while (idx + 1 < xpaths.Length)
                {
                    path += "/";
                    path += xpaths[idx];
                    idx++;
                }

                TextAsset file = ABLoader.current.LoadAsset <TextAsset>(path, xpaths[idx] + ".lua");
                if (file != null)
                {
                    return(file.bytes);
                }
                else
                {
                    file = ABLoader.current.LoadAsset <TextAsset>(path + "/lualib", xpaths[idx] + ".lua");
                    if (file != null)
                    {
                        return(file.bytes);
                    }
                    return(null);
                }
            });
            _luaenv.DoString(@" require 'main' ");
            Main main = _luaenv.Global.Get <Main>("main");

            Bacon.Lua.ILuaPool pool = main();
            Maria.Lua.LuaPool.Instance.Cache <Bacon.Lua.ILuaPool>(pool);
        }
示例#9
0
    void initXLua()
    {
        Debug.Log("Init XLua");

        luaEnv         = new XLua.LuaEnv();
        XLua.Utils.Lua = luaEnv;

        luaEnv.AddBuildin("rapidjson", XLua.LuaDLL.Lua.LoadRapidJson);

        luaEnv.AddLoader((ref string path) => {
            string realpath = path.Replace('.', '/');

            if (useAssetBundle)
            {
                if (!realpath.Contains("xlua/"))
                {
                    realpath           = ("assets/bytecode/" + realpath + ".bytes").ToLower();
                    string abName      = ResourceManager.Instance.LookupAssetBundleName(realpath);
                    AssetBundle bundle = ResourceManager.Instance.LoadAssetBundle(abName);
                    TextAsset ta       = bundle.LoadAsset <TextAsset>(realpath);
                    if (ta != null)
                    {
                        return(ta.bytes);
                    }
                }
            }
            else
            {
                realpath = XLua.LuaEnv.LuaDir + "/" + realpath + ".lua";
                if (File.Exists(realpath))
                {
                    return(File.ReadAllBytes(realpath));
                }
            }

            return(null);
        });
    }
示例#10
0
        static int _m_AddLoader(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                XLua.LuaEnv gen_to_be_invoked = (XLua.LuaEnv)translator.FastGetCSObj(L, 1);



                {
                    XLua.LuaEnv.CustomLoader _loader = translator.GetDelegate <XLua.LuaEnv.CustomLoader>(L, 2);

                    gen_to_be_invoked.AddLoader(_loader);



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
示例#11
0
        /// <summary>
        /// 添加require的加载文件方法
        /// </summary>
        private void AddLoaders()
        {
            var _conf = GameState.Conf.GameStateConf.GetInstance();

            foreach (string luaFilePrefix in _conf.Data.LuaFilePrefixs)
            {
                foreach (string luaFileSuffix in _conf.Data.LuaFileSuffixs)
                {
                    _luaEnv.AddLoader((ref string filename) =>
                    {
                        string filePath = string.Format("{0}{1}{2}", luaFilePrefix, filename, luaFileSuffix);
                        var luaText     = AssetBundles.DataLoader.Load <TextAsset>(filePath);
                        if (luaText != null)
                        {
                            return(System.Text.Encoding.UTF8.GetBytes(luaText.text));
                        }
                        else
                        {
                            return(null);
                        }
                    });
                }
            }
        }
示例#12
0
    void Start()
    {
        mState = new XLua.LuaEnv();

        // xLuaHook important ------------------
        // open xlua debug hook library
        XLua.LuaHook.OpenDebug(mState.rawL);

        mState.AddLoader(GetDecodeContent);
#if UNITY_EDITOR
        AutoAddSearchPath(Application.dataPath + "/LuaScripts");

        // xLuaHook important ------------------
        // add xlua debug hook path
        AutoAddSearchPath(Application.dataPath + "/XLuaHook/LuaScripts");
#endif

        mState.DoString("require(\"Main\")");
        mLuaUpdate  = mState.Global.Get <LuaUpdateDelegate>("GlobalUpdate");
        mLuaInit    = mState.Global.Get <LuaInitDelegate>("GlobalInit");
        mLuaDestroy = mState.Global.Get <LuaDestroyDelegate>("GlobalDestroy");

        mLuaInit();
    }
示例#13
0
        public Application(Maria.Util.App app)
        {
            _app    = app;
            _tiSync = new TimeSync();
            _tiSync.LocalTime();
            _lastTi = _tiSync.LocalTime();

#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            //_cotype = CoType.THREAD;
            _cotype = CoType.CO;
#elif UNITY_IOS || UNITY_ANDROID
            _cotype = CoType.CO;
#endif
            if (_cotype == CoType.THREAD)
            {
                _semaphore           = new Semaphore(1, 1);
                _worker              = new Thread(new ThreadStart(Worker));
                _worker.IsBackground = true;
                _worker.Start();
                UnityEngine.Debug.LogWarning("create thread success.");
            }
            else
            {
                UnityEngine.Debug.LogWarning("create co success.");
            }
            _luaenv = new XLua.LuaEnv();
            _luaenv.AddBuildin("cjson", XLua.LuaDLL.Lua.LoadCJson);
            _luaenv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg);
            _luaenv.AddBuildin("sproto.core", XLua.LuaDLL.Lua.LoadSprotoCore);
            _luaenv.AddLoader((ref string filepath) => {
                UnityEngine.Debug.LogFormat("LUA custom loader {0}", filepath);

                string[] xpaths = filepath.Split(new char[] { '.' });
                string path     = "xlua/src";
                int idx         = 0;
                while (idx + 1 < xpaths.Length)
                {
                    path += "/";
                    path += xpaths[idx];
                    idx++;
                }

                TextAsset file = ABLoader.current.LoadAsset <TextAsset>(path, xpaths[idx] + ".lua");
                if (file != null)
                {
                    return(file.bytes);
                }
                else
                {
                    file = ABLoader.current.LoadAsset <TextAsset>(path + "/lualib", xpaths[idx] + ".lua");
                    if (file != null)
                    {
                        return(file.bytes);
                    }
                    return(null);
                }
            });
            _luaenv.DoString(@"
require 'main'
");
        }