Exemple #1
0
        /// <summary>
        /// 新建一个新的lua虚拟机
        /// </summary>
        public static void New(string script)
        {
            if (tokenSource != null)
            {
                tokenSource.Dispose();
            }
            tokenSource = new CancellationTokenSource();//task取消指示

            lua       = LuaEnv.CreateLuaEnv();
            isRunning = true;
            Task.Run(() =>
            {
                try
                {
                    lua.Global.SetInPath("sys", lua.DoString(Global.Utils.GetAssetsFileContent("/Assets/script/sys.lua"))[0]);
                    lua.DoString("apiStartTimer = CS.LUATeach.LuaEnv.LuaRunEnv.StartTimer");
                    lua.DoString("apiStopTimer = CS.LUATeach.LuaEnv.LuaRunEnv.StopTimer");
                    lua.DoString("setRunMaxSeconds(-1)");
                    lua.DoString(script);
                }
                catch (Exception ex)
                {
                    StopLua(ex.Message);
                }
                runTigger();
            }, tokenSource.Token);
        }
Exemple #2
0
        /// <summary>
        /// 新建一个新的lua虚拟机
        /// </summary>
        public static void New(string file)
        {
            canRun    = false;
            isRunning = true;
            if (tokenSource != null)
            {
                tokenSource.Dispose();
            }
            tokenSource = new CancellationTokenSource();//task取消指示

            //文件不存在
            if (!File.Exists(Tools.Global.ProfilePath + file))
            {
                return;
            }
            lua = new XLua.LuaEnv();
            Task.Run(() =>
            {
                while (!canRun)
                {
                    Task.Delay(100).Wait();
                }
                try
                {
                    lua.Global.SetInPath("runType", "script");//一次性处理标志
                    LuaLoader.Initial(lua);
                    lua.DoString($"require '{file.Replace("/",".").Substring(0,file.Length-4)}'");
                }
                catch (Exception ex)
                {
                    StopLua(ex.ToString());
                }
            }, tokenSource.Token);
        }
Exemple #3
0
        /// <summary>
        /// 初始化lua对象
        /// </summary>
        /// <param name="lua"></param>
        public static void Initial(XLua.LuaEnv lua, string t = "script")
        {
            //utf8转gbk编码的hex值
            lua.DoString("apiUtf8ToHex = CS.llcom.LuaEnv.LuaApis.Utf8ToAsciiHex");
            //获取软件目录路径
            lua.DoString("apiGetPath = CS.llcom.LuaEnv.LuaApis.GetPath");
            //输出日志
            lua.DoString("apiPrintLog = CS.llcom.LuaEnv.LuaApis.PrintLog");
            //获取快捷发送区数据
            lua.DoString("apiQuickSendList = CS.llcom.LuaEnv.LuaApis.QuickSendList");
            //输入框
            lua.DoString("apiInputBox = CS.llcom.LuaEnv.LuaApis.InputBox");

            if (t != "send")
            {
                //发送串口数据
                lua.DoString("apiSendUartData = CS.llcom.LuaEnv.LuaApis.SendUartData");
                //定时器
                lua.DoString("apiStartTimer = CS.llcom.LuaEnv.LuaRunEnv.StartTimer");
                lua.DoString("apiStopTimer = CS.llcom.LuaEnv.LuaRunEnv.StopTimer");
            }

            //运行初始化文件
            lua.DoString("require 'core_script.head'");
        }
        public XLua.LuaEnv __Gen_Delegate_Imp23(object p0)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int err_func   = LuaAPI.load_error_func(L, errorFuncRef);
            ObjectTranslator translator = luaEnv.translator;

            LuaAPI.lua_getref(L, luaReference);

            translator.PushAny(L, p0);

            int __gen_error = LuaAPI.lua_pcall(L, 1, 1, err_func);
            if (__gen_error != 0)
            {
                luaEnv.ThrowExceptionFromError(err_func - 1);
            }


            XLua.LuaEnv __gen_ret = (XLua.LuaEnv)translator.GetObject(L, err_func + 1, typeof(XLua.LuaEnv));
            LuaAPI.lua_settop(L, err_func - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
Exemple #5
0
        public ErrorCode Initialize(Options opts)
        {
#if !DISABLE_LUA
            XLua.XLuaGenIniterRegister.Init();
            XLua.WrapPusher.Init();
            XLua.DelegatesGensBridge.Init();

            this._luaEnv = new XLua.LuaEnv();
            this._luaEnv.AddLoader(( ref string filepath ) => File.ReadAllBytes(Path.Combine(opts.scriptPath, filepath + ".lua")));
            this._luaEnv.DoString("require \"cs\"");
#endif
            this.config           = new CSConfig();
            this.config.defPath   = opts.defs;
            this.config.goodsPath = opts.goods;
            if (string.IsNullOrEmpty(opts.cfg))
            {
                this.config.CopyFromCLIOptions(opts);
            }
            else
            {
                this.config.CopyFromJson(( Hashtable )MiniJSON.JsonDecode(File.ReadAllText(opts.cfg)));
            }

            this.matchMgr.InitFromDefs(( Hashtable )MiniJSON.JsonDecode(File.ReadAllText(this.config.matchDefs)));

            this.LoadDefs();
            this.LoadGoods();
            return(ErrorCode.Success);
        }
Exemple #6
0
        public ErrorCode Initialize(Options opts)
        {
#if !DISABLE_LUA
            XLua.XLuaGenIniterRegister.Init();
            XLua.WrapPusher.Init();
            XLua.DelegatesGensBridge.Init();

            this._luaEnv = new XLua.LuaEnv();
            this._luaEnv.AddLoader(( ref string filepath ) => File.ReadAllBytes(Path.Combine(opts.scriptPath, filepath + ".lua")));
            this._luaEnv.DoString("require \"gs\"");
#endif
            this.config         = new GSConfig();
            this.config.defPath = opts.defs;
            if (string.IsNullOrEmpty(opts.cfg))
            {
                this.config.CopyFromCLIOptions(opts);
                return(ErrorCode.Success);
            }
            try
            {
                this.config.CopyFromJson(( Hashtable )MiniJSON.JsonDecode(File.ReadAllText(opts.cfg)));
            }
            catch (Exception e)
            {
                Logger.Error(e);
                return(ErrorCode.CfgLoadFailed);
            }
            this.ReloadDefs();
            return(ErrorCode.Success);
        }
Exemple #7
0
        /// <summary>
        /// 运行lua文件并获取结果
        /// </summary>
        /// <param name="file"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string Run(string file, ArrayList args = null)
        {
            //文件不存在
            if (!File.Exists(Tools.Global.ProfilePath + "user_script_send_convert/" + file))
            {
                return("");
            }

            using (var lua = new XLua.LuaEnv())
            {
                try
                {
                    lua.Global.SetInPath("runType", "send");//一次性处理标志
                    lua.Global.SetInPath("file", file);
                    Initial(lua, "send");
                    if (args != null)
                    {
                        for (int i = 0; i < args.Count; i += 2)
                        {
                            lua.Global.SetInPath((string)args[i], args[i + 1].ToString());
                        }
                    }
                    return(lua.DoString("return require'core_script.once'")[0].ToString());
                }
                catch (Exception e)
                {
                    throw new Exception(e.ToString());
                }
            }
        }
Exemple #8
0
        public Application(XLua.LuaEnv env)
        {
            _luaenv = env;
            _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.Log("create thread success.");
            }
            else
            {
                UnityEngine.Debug.Log("create co success.");
            }
        }
Exemple #9
0
        protected override void OnInit()
        {
            base.OnInit();
            AppLog.Debug("CoreTestModule OnInit");

            m_luaEnv = Lua.LuaUtil.NewLuaEnv();
        }
Exemple #10
0
        private void Start()
        {
            GPerfMonitor.GetInstance().OpenRecorder(RecorderType.Remote);
#if GPERF_XLUA
            XLua.LuaEnv env = wt.framework.XLuaManager.Instance.GetLuaEnv();
            GPerfMonitor.GetInstance().SetLuaEnv(env);
#endif
        }
Exemple #11
0
        public override void OnInstance()
        {
            m_luaVM = new XLua.LuaEnv();
            m_luaVM.AddLoader(ResourceLoader.LoadLua);

            m_luaVM.GcPause   = 100;
            m_luaVM.GcStepmul = 5000;
        }
Exemple #12
0
 public static XLua.LuaEnv NewLuaEnv()
 {
     XLua.LuaEnv env = new XLua.LuaEnv();
     XLua.LuaDLL.Lua.register_3rd_lualibs(env.L);
     XLua.LuaDLL.Lua.RapidJsonAddBuildin(env);
     XLua.LuaDLL.Lua.PbAddBuildin(env);
     XLua.LuaDLL.Lua.SprotoAddBuildin(env);
     XLua.LuaDLL.Lua.LpegAddBuildin(env);
     return(env);
 }
Exemple #13
0
 protected override void OnInit()
 {
     base.OnInit();
     AppLog.Debug("CoreTestModule OnInit");
     m_msgNetAgent        = new MsgNetAgent();
     m_msgHandler         = new TestMsgNetAgentHandler();
     m_msgHandler.m_owner = this;
     m_msgNetAgent.SetHandler(m_msgHandler);
     m_luaEnv = Lua.LuaUtil.NewLuaEnv();
 }
Exemple #14
0
        // Start is called before the first frame update
        void Start()
        {
            Debug.Assert(Singleton == null);
            Singleton = this;
            DontDestroyOnLoad(this.gameObject);

            m_luaEnv = new XLua.LuaEnv();
            m_luaEnv.AddLoader(xLuaLoader.LoadFromResource);
            m_luaEnv.Global.Set("launch_file", ms_launchFile);
            m_luaEnv.DoString(Resources.Load <TextAsset>("runtime").text, "runtime");
        }
Exemple #15
0
        public void CustomDestroy()
        {
            if (null == m_luaVM)
            {
                return;
            }

            m_luaVM.Dispose();
            m_luaVM = null;

            Debug.Log("~LuaManager was destroyed!");
        }
Exemple #16
0
 private void OnDestroy()
 {
     if (m_luaEnv != null)
     {
         m_luaEnv.DoString("__lua_runtime__.Cleanup()");
         m_luaEnv.Dispose();
     }
     m_luaEnv = null;
     if (Singleton == this)
     {
         Singleton = null;
     }
 }
Exemple #17
0
        /// <summary>
        /// 新建Lua虚拟机,并绑定好各项接口
        /// </summary>
        /// <returns></returns>
        public static XLua.LuaEnv CreateLuaEnv()
        {
            var lua = new XLua.LuaEnv();

            //utf8转gbk编码的hex值
            lua.DoString("apiUtf8ToHex = CS.LUATeach.LuaEnv.LuaApi.Utf8ToAsciiHex");
            //获取软件目录路径
            lua.DoString("apiGetPath = CS.LUATeach.LuaEnv.LuaApi.GetPath");
            //输出日志
            lua.DoString("apiPrintLog = CS.LUATeach.LuaEnv.LuaApi.PrintLog");

            //运行初始化文件
            lua.DoString(Global.Utils.GetAssetsFileContent("/Assets/script/head.lua"));
            lua.DoString(Global.Utils.GetAssetsFileContent("/Assets/script/strings.lua"));
            lua.Global.SetInPath("log", lua.DoString(Global.Utils.GetAssetsFileContent("/Assets/script/log.lua"))[0]);
            lua.Global.SetInPath("JSON", lua.DoString(Global.Utils.GetAssetsFileContent("/Assets/script/JSON.lua"))[0]);

            return(lua);
        }
Exemple #18
0
        /// <summary>
        /// 初始化lua对象
        /// </summary>
        /// <param name="lua"></param>
        public static void Initial(XLua.LuaEnv lua, string t = "script")
        {
            //utf8转gbk编码的hex值
            lua.DoString("apiUtf8ToHex = CS.llcom.LuaEnv.LuaApis.Utf8ToAsciiHex");
            //获取软件目录路径
            lua.DoString("apiGetPath = CS.llcom.LuaEnv.LuaApis.GetPath");
            //输出日志
            lua.DoString("apiPrintLog = CS.llcom.LuaEnv.LuaApis.PrintLog");
            //获取快捷发送区数据
            lua.DoString("apiQuickSendList = CS.llcom.LuaEnv.LuaApis.QuickSendList");
            //输入框
            lua.DoString("apiInputBox = CS.llcom.LuaEnv.LuaApis.InputBox");

            if (t != "send")
            {
                //发送串口数据
                lua.DoString("apiSendUartData = CS.llcom.LuaEnv.LuaApis.SendUartData");
                //定时器
                lua.DoString("apiStartTimer = CS.llcom.LuaEnv.LuaRunEnv.StartTimer");
                lua.DoString("apiStopTimer = CS.llcom.LuaEnv.LuaRunEnv.StopTimer");
            }

            //加上需要require的路径
            lua.DoString(@"
local rootPath = '" + LuaApis.Utf8ToAsciiHex(LuaApis.GetPath()) + @"'
rootPath = rootPath:gsub('[%s%p]', ''):upper()
rootPath = rootPath:gsub('%x%x', function(c)
                                    return string.char(tonumber(c, 16))
                                end)
package.path = package.path..
';'..rootPath..'core_script/?.lua'..
';'..rootPath..'?.lua'..
';'..rootPath..'user_script_run/requires/?.lua'
package.cpath = package.cpath..
';'..rootPath..'core_script/?.lua'..
';'..rootPath..'?.lua'..
';'..rootPath..'user_script_run/requires/?.lua'
");

            //运行初始化文件
            lua.DoString("require 'core_script.head'");
        }
Exemple #19
0
 /// <summary>
 /// 停止运行lua
 /// </summary>
 public static void StopLua(string ex)
 {
     LuaRunError(null, EventArgs.Empty);
     if (ex != "")
     {
         LuaApis.PrintLog("lua代码报错了:\r\n" + ex);
     }
     else
     {
         LuaApis.PrintLog("lua代码已停止");
     }
     foreach (var v in pool)
     {
         v.Value.Cancel();
     }
     isRunning = false;
     tokenSource.Cancel();
     pool.Clear();
     lua = null;
 }
Exemple #20
0
        public XLua.LuaEnv __Gen_Delegate_Imp25()
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;

            PCall(L, 0, 1, errFunc);


            XLua.LuaEnv __gen_ret = (XLua.LuaEnv)translator.GetObject(L, errFunc + 1, typeof(XLua.LuaEnv));
            LuaAPI.lua_settop(L, errFunc - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
Exemple #21
0
        public void __Gen_Delegate_Imp12(XLua.LuaEnv p0, XLua.ObjectTranslator p1)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;
            translator.Push(L, p0);
            translator.Push(L, p1);

            PCall(L, 2, 0, errFunc);



            LuaAPI.lua_settop(L, errFunc - 1);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
Exemple #22
0
        /// <summary>
        /// 运行lua文件并获取结果
        /// </summary>
        /// <param name="file"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public static string Run(string file, ArrayList args = null)
        {
            //文件不存在
            if (!File.Exists(Tools.Global.ProfilePath + "user_script_send_convert/" + file))
            {
                return("");
            }

            if (luaRunner == null)
            {
                luaRunner = new XLua.LuaEnv();
                luaRunner.Global.SetInPath("runType", "send");//一次性处理标志
                Initial(luaRunner, "send");
            }
            lock (luaRunner)
            {
                luaRunner.Global.SetInPath("file", file);

                try
                {
                    if (args != null)
                    {
                        for (int i = 0; i < args.Count; i += 2)
                        {
                            luaRunner.Global.SetInPath((string)args[i], args[i + 1].ToString());
                            System.Diagnostics.Debug.WriteLine($"{(string)args[i]},{args[i + 1]}");
                        }
                    }
                    return(luaRunner.DoString("return require('core_script.once')()")[0].ToString());
                }
                catch (Exception e)
                {
                    luaRunner.Dispose();
                    luaRunner = null;
                    throw new Exception(e.ToString());
                }
            }
        }
Exemple #23
0
        public XLua.LuaBase __Gen_Delegate_Imp11(int p0, XLua.LuaEnv p1)
        {
#if THREAD_SAFE || HOTFIX_ENABLE
            lock (luaEnv.luaEnvLock)
            {
#endif
            RealStatePtr L = luaEnv.rawL;
            int errFunc    = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
            ObjectTranslator translator = luaEnv.translator;
            LuaAPI.xlua_pushinteger(L, p0);
            translator.Push(L, p1);

            PCall(L, 2, 1, errFunc);


            XLua.LuaBase __gen_ret = (XLua.LuaBase)translator.GetObject(L, errFunc + 1, typeof(XLua.LuaBase));
            LuaAPI.lua_settop(L, errFunc - 1);
            return(__gen_ret);

#if THREAD_SAFE || HOTFIX_ENABLE
        }
#endif
        }
Exemple #24
0
 static Module()
 {
     luaEnv = new XLua.LuaEnv();
     //luaEnv.AddLoader(LuaLoader);
 }
Exemple #25
0
 // Start is called before the first frame update
 void Start()
 {
     XLua.LuaEnv luaenv = new XLua.LuaEnv();
     luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')");
     luaenv.Dispose();
 }
Exemple #26
0
 static Patch()
 {
     patchLuaEnv = new XLua.LuaEnv();
     patchLuaEnv.AddLoader(PatchLuaLoader);
 }
Exemple #27
0
 public void SetLuaEnv(XLua.LuaEnv luaEnv)
 {
     XLuaEnv = luaEnv;
 }
 public void Register(XLua.LuaEnv luaState)
 {
     instance = this;
 }
Exemple #29
0
        public static void OnCreateServerSkillTime()
        {
            //遍历文件夹

            string path            = AssetBundleUtility.PackagePathToAssetsPath("Lua");
            string AssetbundleName = AssetBundleUtility.AssetBundlePathToAssetBundleName(path);

            XLua.LuaEnv luaEnv = new XLua.LuaEnv();
            luaEnv.AddLoader(CustomLoader);
            luaEnv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadPb);
            luaEnv.AddBuildin("cjson", XLua.LuaDLL.Lua.LoadRapidJson);
            string cmd = string.Format("require('{0}/Editor/AssetBundle/SkillTimeline')", Application.dataPath);

            luaEnv.DoString(cmd);
            XLua.LuaFunction func = luaEnv.Global.Get <XLua.LuaFunction>("ParseSkillTime");
            object[]         obj  = func.Call();
            if (obj != null && obj.Length > 0)
            {
                string serverPath = string.Format("{0}/{1}.txt", Application.dataPath.Substring(0, Application.dataPath.Length - 7), "normal_timeline");
                if (File.Exists(serverPath))
                {
                    File.Delete(serverPath);
                }

                FileStream   fs = new FileStream(serverPath, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("id" + "\t" + "roleId" + "\t" + "key" + "\t" + "time");
                sw.WriteLine();
                sw.Write("int" + "\t" + "int" + "\t" + "string" + "\t" + "float");
                sw.WriteLine();

                XLua.LuaTable tempTable = obj[0] as XLua.LuaTable;
                int           index     = 1;
                tempTable.ForEach <int, XLua.LuaTable>(delegate(int a, XLua.LuaTable luaTable) {
                    sw.Write(index + "\t" + luaTable.Get <int>("roldId") + "\t" + luaTable.Get <string>("key")
                             + "\t" + luaTable.Get <float>("time"));
                    sw.WriteLine();
                    index++;
                });

                sw.Close();
                fs.Close();
            }

            func = luaEnv.Global.Get <XLua.LuaFunction>("ParseCSkillTime");
            obj  = func.Call();
            if (obj != null && obj.Length > 0)
            {
                string serverPath = string.Format("{0}/{1}.txt", Application.dataPath.Substring(0, Application.dataPath.Length - 7), "cc_timeline");
                if (File.Exists(serverPath))
                {
                    File.Delete(serverPath);
                }

                FileStream   fs = new FileStream(serverPath, FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                sw.Write("id" + "\t" + "key" + "\t" + "time");
                sw.WriteLine();
                sw.Write("int" + "\t" + "string" + "\t" + "float");
                sw.WriteLine();

                XLua.LuaTable tempTable = obj[0] as XLua.LuaTable;
                int           index     = 1;
                tempTable.ForEach <int, XLua.LuaTable>(delegate(int a, XLua.LuaTable luaTable) {
                    sw.Write(index + "\t" + luaTable.Get <string>("key")
                             + "\t" + luaTable.Get <float>("time"));
                    sw.WriteLine();
                    index++;
                });

                sw.Close();
                fs.Close();
            }
        }
Exemple #30
0
 public void Register(XLua.LuaEnv luaState)
 {
     _instance = this;
     luaState.Global.Set("SceneService", this);
 }