/// <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); }
protected override void OnStart() { m_lua.AddLoader(LuaFileLoader); object[] ret = null; ret = m_lua.DoString(string.Format("entrance_arg_str = '{0}' ", m_owner.app.root.lua_main_args)); ret = m_lua.DoString(" require 'prepare_env' "); // ret = m_lua.DoString(string.Format(" {0}('{1}') ", m_owner.app.root.lua_main_fn, m_owner.app.root.lua_main_args)); }
public object[] DoString(string str) { if (null == m_luaVM) { return(null); } return(m_luaVM.DoString(str)); }
/// <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'"); }
/// <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()); } } }
/// <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); }
public static void Start() { if (!System.IO.Directory.Exists(Define.moduleLocalDirectory)) { System.IO.Directory.CreateDirectory(Define.moduleLocalDirectory); } luaEnv.DoString("require('main')"); luaEnv.Global.Get("OnClick", out luaOnClick); }
/// <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'"); }
// 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"); }
private void OnDestroy() { if (m_luaEnv != null) { m_luaEnv.DoString("__lua_runtime__.Cleanup()"); m_luaEnv.Dispose(); } m_luaEnv = null; if (Singleton == this) { Singleton = null; } }
static void DoPatch() { var localCode = remotePatchID; UnityEngine.PlayerPrefs.SetInt("PatchID", localCode); if (System.IO.File.Exists(Define.patchFullname)) { patchLuaEnv.DoString("require 'hotfix'"); } Event.Brocast("EventOnPatchStateChanged", "Excute Patch"); }
void OnGUI() { if (UnityEngine.GUI.Button(new UnityEngine.Rect(10, 10, 300, 80), "Hotfix")) { luaenv.DoString(@" xlua.hotfix(CS.DataManager, 'Update', function(self) self.tick = self.tick + 1 if (self.tick % 200) == 0 then print('<<<<<<<<Update in lua, tick = ' .. self.tick) end end) "); } }
protected override void OnUpdate() { base.OnUpdate(); // AppLog.Debug("CoreTestModule OnUpdate"); if (m_firstUpdate) { m_firstUpdate = false; m_msgNetAgent.Connect("127.0.0.1", 31000); Core.ins.net.AddNetAgent(m_msgNetAgent); // test lua json m_luaEnv.DoString(@" json = require('rapidjson'); print(json.decode('{}')) "); } }
/// <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); }
/// <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()); } } }
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(); } }
// Parse the command and try to execute it public static void ExecuteCommand(string command) { if (command == null) { return; } command = command.Trim(); if (command.Length == 0) { return; } if (command.Substring(0, 4).ToLower() == "lua:") { var env = new XLua.LuaEnv(); env.DoString(command.Substring(4)); env.Dispose(); return; } for (int i = 0, imax = m_commondActions.Count; i < imax; i++) { if (m_commondActions[i](command)) { return; } } // Parse the arguments commandArguments.Clear(); int endIndex = IndexOfChar(command, ' ', 0); commandArguments.Add(command.Substring(0, endIndex)); for (int i = endIndex + 1; i < command.Length; i++) { if (command[i] == ' ') { continue; } int delimiterIndex = IndexOfDelimiter(command[i]); if (delimiterIndex >= 0) { endIndex = IndexOfChar(command, inputDelimiters[delimiterIndex][1], i + 1); commandArguments.Add(command.Substring(i + 1, endIndex - i - 1)); } else { endIndex = IndexOfChar(command, ' ', i + 1); commandArguments.Add(command.Substring(i, endIndex - i)); } i = endIndex; } // Check if command exists ConsoleMethodInfo methodInfo; if (!methods.TryGetValue(commandArguments[0], out methodInfo)) { Debug.LogWarning("Can't find command: " + commandArguments[0]); } else if (!methodInfo.IsValid()) { Debug.LogWarning("Method no longer valid (instance dead): " + commandArguments[0]); } else { // Check if number of parameter match if (methodInfo.parameterTypes.Length != commandArguments.Count - 1) { Debug.LogWarning("Parameter count mismatch: " + methodInfo.parameterTypes.Length + " parameters are needed"); return; } Debug.Log("Executing command: " + commandArguments[0]); // Parse the parameters into objects object[] parameters = new object[methodInfo.parameterTypes.Length]; for (int i = 0; i < methodInfo.parameterTypes.Length; i++) { string argument = commandArguments[i + 1]; Type parameterType = methodInfo.parameterTypes[i]; ParseFunction parseFunction; if (!parseFunctions.TryGetValue(parameterType, out parseFunction)) { Debug.LogError("Unsupported parameter type: " + parameterType.Name); return; } object val; if (!parseFunction(argument, out val)) { Debug.LogError("Couldn't parse " + argument + " to " + parameterType.Name); return; } parameters[i] = val; } // Execute the method associated with the command object result = methodInfo.method.Invoke(methodInfo.instance, parameters); if (methodInfo.method.ReturnType != typeof(void)) { // Print the returned value to the console if (result == null || result.Equals(null)) { Debug.Log("Value returned: null"); } else { Debug.Log("Value returned: " + result.ToString()); } } } }
// 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(); }