// Use this for initialization void Start() { LuaEnv luaenv = new LuaEnv(); luaenv.DoString(script); CalcNew calc_new = luaenv.Global.GetInPath<CalcNew>("Calc.New"); ICalc calc = calc_new(10, "hi", "john"); //constructor Debug.Log("sum(*10) =" + calc.Add(1, 2)); calc.Mult = 100; Debug.Log("sum(*100)=" + calc.Add(1, 2)); luaenv.Dispose(); }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.AddLoader((ref string filename) => { if (filename == "InMemory") { string script = "return {ccc = 9999}"; return System.Text.Encoding.UTF8.GetBytes(script); } return null; }); luaenv.DoString("print('InMemory.ccc=', require('InMemory').ccc)"); }
//初始化 public override void Init() { mSearchPaths = new List <string>(); mMatterFunctionMap = new Dictionary <string, LuaFunction>(); AddEditorSearchPath(ScriptBaseSetting.LuaGamePath); mLuaEnv = new LuaEnv(); mLuaEnv.AddLoader(XLuaLoader); var enterFile = LuaEnterFile; mLuaEnv.DoString(XLuaLoader(ref enterFile)); AddMatterFunction(MatterFunctionName.CreateLuaFile); AddMatterFunction(MatterFunctionName.MonoUpdate); }
public void TestImplementLogic() { //try to do a simple logic of calendar //TODO: write a lua script name "TestImplement.lua.txt" _luaEnv.DoString("require 'TestImplement'"); CalendarNew cal_new = _luaEnv.Global.GetInPath <CalendarNew>("Calendar.New"); if ((int)System.DateTime.DaysInMonth(2004, 2) - (int)cal_new().Days_In_Month(2004, 2) != 0) { throw new Exception("Not same day of month"); } DateTime dt = new DateTime(2019, 9, 20); if ((int)dt.DayOfWeek - cal_new().Day_Of_Week(2019, 9, 20) != 0) { throw new Exception("Not same day of week"); } Debug.Log("Case 2 : pass "); }
void Start() { BagMgr.Instance.InitItemInfo(); UIMgr.Instance.OpenUI("UIMain"); //test ABMgr ABMgr.Instance.LoadResAsync <GameObject>("model", "cube", (obj) => { Instantiate(obj); }); env = new LuaEnv(); env.DoString("require 'Lua/Main'"); }
public object[] DoScript(string luaScriptName, string chunkName, LuaTable env) { if (m_LuaEnv == null) { Log.Error("LuaEnv is invalid."); return(null); } if (string.IsNullOrEmpty(luaScriptName)) { Log.Error("Lua script name is invalid."); return(null); } byte[] luaScriptBytes = null; if (!m_LuaScriptCache.TryGetValue(luaScriptName, out luaScriptBytes)) { Log.Warning("Can not find lua script '{0}', please LoadScript first.", luaScriptName); return(null); } return(m_LuaEnv.DoString(luaScriptBytes, chunkName, env)); }
void OnGUI() { if (GUI.Button(new Rect(10, 100, 300, 150), "Hotfix")) { luaenv.DoString(@" xlua.hotfix(CS.HotfixTest, 'Update', function(self) self.tick = self.tick + 1 if (self.tick % 50) == 0 then print('<<<<<<<<Update in lua, tick = ' .. self.tick) end end) "); } }
/// <summary> /// 载入所有脚本 /// </summary> /// <returns>成功返回true</returns> public bool LoadScripts() { luaEnv.DoString(booterscript, "LuaBooter", scriptEnv); LuaBehaviourManager.Instance.Init(); var loader = luaEnv.Global.Get <ILuaScriptsLoader>("GameBooter"); loader.ReloadScripts(); OnLuaScriptLoaded(); return(true); }
// Use this for initialization void Start() { LuaEnv luaenv = new LuaEnv(); luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')"); luaenv.DoString("CS.UnityEngine.Debug.LogError('hello world')"); //加载lua文件 luaenv.DoString("require 'byfile'"); // 加载自定义文件 loader luaenv.AddLoader((ref string fileName) => { if (fileName == "test") { string script = "return {ccc = 9999}"; return(System.Text.Encoding.UTF8.GetBytes(script)); } return(null); }); luaenv.DoString("print('test.ccc=',require('test').ccc)"); luaenv.Dispose(); }
// Start is called before the first frame update void Start() { XLua.LuaEnv env = new LuaEnv(); env.AddLoader(MyLoader); env.DoString("require 'CSharpCallLua'");//调用完才能取得里面的变量 Person p = env.Global.Get <Person>("person"); print(p.name + "-" + p.age); p.name = "Akimoto"; env.DoString("print(person.name)"); IPerson Ip = env.Global.Get <IPerson>("person"); print("IP" + Ip.name); ListTest(env); env.Dispose(); //int a = env.Global.Get<int>("a");//获取lua里面的全局变量a //print(a); //string str = env.Global.Get<string>("str");//获取lua里面的全局变量str //print(str); //bool isDie = env.Global.Get<bool>("isDie");//获取lua里面的全局变量isDie //print(isDie); //env.Dispose(); }
void Awake() { LuaEnv luaenvScriptCtrl = new LuaEnv(); LuaEnv.CustomLoader method = CustomLoaderMethod; luaenvScriptCtrl.AddLoader(method); if (xluaname == "") { xluaname = this.name; } luaenvScriptCtrl.DoString(@" require('" + xluaname + @"')"); }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.AddLoader((ref string filename) => { if (filename == "InMemory") { string script = "return {ccc = 9999}"; return(System.Text.Encoding.UTF8.GetBytes(script)); } return(null); }); luaenv.DoString("print('InMemory.ccc=', require('InMemory').ccc)"); }
void Awake() { luaEnv = new LuaEnv(); luaEnv.AddBuildin("cjson", XLua.LuaDLL.Lua.LoadCJson); luaEnv.AddBuildin("sproto", XLua.LuaDLL.Lua.LoadSproto); luaEnv.AddBuildin("crypt", XLua.LuaDLL.Lua.LoadCrypt); luaEnv.AddBuildin("lpeg", XLua.LuaDLL.Lua.LoadLpeg); luaEnv.AddBuildin("clonefunc", XLua.LuaDLL.Lua.LoadCloneFunc); luaEnv.DoString(@"local hardreload = require 'hardreload' require = hardreload.require"); luaEnv.DoString(@"require 'ButtonInteraction'"); scriptEnv = luaEnv.Global.Get <LuaTable>("ui");; scriptEnv.Get("start", out luaStart); foreach (var injection in injections) { scriptEnv.Set(injection.name, injection.value); } }
public override void Init() { base.Init(); luaEnv = new LuaEnv(); AddBuildin(); AddLoader(); luaEnv.DoString("require 'Main'"); luaStart = luaEnv.Global.Get <LuaAction>("Start"); luaExit = luaEnv.Global.Get <LuaAction>("Exit"); if (luaStart != null) { luaStart(); } }
// Start is called before the first frame update unsafe void Start() { JsEnv env = new JsEnv(); //JsEnv env = new JsEnv(new DefaultLoader(), 9200); //env.WaitDebugger(); PuertsDLL.SetGlobalFunction(env.isolate, "oldCallback", v8FunctionCallback, 0); // PuertsDLL.SetGlobalFunction(env.isolate, "newCallback", newFunctionCallback, 0); double resultOld = env.Eval <double>(@" for (var i = 0; i < 10000; i++) global.oldCallback(1,2,3,4) var start1 = Date.now(); for (var i = 0; i < 1000000; i++) global.oldCallback(1,2,3,4) Date.now() - start1; "); text1.text = "ts: " + resultOld; // double resultNew = env.Eval<double>(@" // for (var i = 0; i < 10000; i++) // global.newCallback(5,6,7,8) // var start2 = Date.now(); // for (var i = 0; i < 1000000; i++) // global.newCallback(5,6,7,8) // Date.now() - start2; // "); // text2.text = "new: " + resultNew; LuaEnv luaEnv = new LuaEnv(); luaEnv.DoString(@" local aaa = CS.NewBehaviourScript.int4 for i=1,10000,1 do aaa(1,2,3,4); end local starttime = os.clock(); for i=1,1000000,1 do aaa(1,2,3,4); end local endtime = os.clock(); usetime = (endtime - starttime) * 1000 "); text3.text = "lua: " + (int)luaEnv.Global.Get <double>("usetime"); }
void Start() { EnvLua = new LuaEnv(); EnvLua.DoString("require 'CCallLua'"); //获取table测试-By Interface IShip myShip = EnvLua.Global.Get <IShip>("ship"); Debug.Log("By Interface"); Debug.Log("name "+ myShip.name); Debug.Log("year "+ myShip.year); Debug.Log("damage "+ myShip.damage); myShip.Fire(666); }
//public TextAsset luaText; //在Inspector 面板中拖入一个lua文件 void Start() { luaEnv = new LuaEnv(); //第一种方式加载lua脚本 //在Dostring中直接写lua代码,Dostring 第一个参数是一个string,lua代码就包含在其中,但需要注意书写一定要符合lua的规则 luaEnv.DoString("print('hello world')"); //第一种方式变种,因为Dostring中的一个参数本质是一个string类型的所以可以自己存个string然后读取,或者在面板上读取一个TextAsset string luaScript = @"print('helle world')"; luaEnv.DoString(luaScript); //luaEnv.DoString(luaText.text); //加载inspector面板中的lua文件 //第二种方式,通过在DoString中传入require moudle 的方法,虽然都是在Dostring中执行,但是其加载的方式还是有所差异 luaEnv.DoString("require 'helloworld'"); //默认的loader是从Resources文件夹中加载,所以我们需要在Resource文件夹中放入相应的lua脚本。 //后面会将自定义Loader,注意因为Resources下能识别的后缀有限,所以要在lua文件后加.txt //第二种方式变种,自定义Loader去加载,默认的loader会从Resources文件夹下进行加载,但是很多时候我们希望从我们制定的文件下去加载lua程序 //同时在实际项目中,可能会涉及到加密lua文件,然后解密之后再执行,还有从服务器下载lua文件等,这时候都需要用到自定义loader,xlua提供了 //AddLoader()方法来加入自定义的loader luaEnv.AddLoader(MyLoader); luaEnv.DoString("require 'helloworldFormLuaFile.lua'"); }
public Script(IScriptable owner, LuaEnv luaEnv, string scriptId) { string ownerId = owner.rid.Replace('@', '_'); this._scriptEnv = luaEnv.NewTable(); this._scriptEnv.Set("owner", owner); luaEnv.Global.Set(ownerId, this._scriptEnv); scriptId = Defs.GetScript(scriptId); if (!string.IsNullOrEmpty(scriptId)) { scriptId = scriptId.Replace("[T]", ownerId); luaEnv.DoString(scriptId); } }
void Start() { //启动lua LuaEnv env = new LuaEnv(); env.AddLoader(myLuaLoader); mainLuaTable = env.DoString("return require 'main'")[0] as LuaTable; LuaFunction startFunc = mainLuaTable.GetInPath <LuaFunction>("start") as LuaFunction; updateFunc = mainLuaTable.GetInPath <LuaFunction>("update") as LuaFunction; fixedUpdateFunc = mainLuaTable.GetInPath <LuaFunction>("fixedUpdate") as LuaFunction; lateUpdateFunc = mainLuaTable.GetInPath <LuaFunction>("lateUpdate") as LuaFunction; startFunc.Call(); }
/// <summary> /// 2.通过接口获得表 /// </summary> void GetLuaTableByInterface() { //自动将表的键值对映射到接口的对应名字字段里.注意这里是引用,会修改表person的内容 IPerson p = luaEnv.Global.Get <IPerson>("person"); print("p:" + p.name + "---" + p.age); //修改接口的内容看表的内容会不会跟着改变 p.name = "陈华大"; p.age = 30; luaEnv.DoString("print(person.name..':'..person.age)"); p.showinf(50, 30); }
/// <summary> /// 加载lua代码块 /// </summary> /// <param name="_luaScript"></param> public void DoString(string _luaScript, string _chunkName = "chunk", LuaTable _luaTable = null) { if (luaEnv != null) { try { luaEnv.DoString(_luaScript, _chunkName, _luaTable); } catch (System.Exception ex) { Debug.Log(ex.Message); } } }
public void Init() { //1. 实例化 xlua引擎 luaEnv = new LuaEnv(); //#if DISABLE_ASSETBUNDLE && UNITY_EDITOR //2.设置xLua的脚本路径 luaEnv.DoString(string.Format("package.path = '{0}/?.bytes'", Application.dataPath + "/Download/xLuaLogic/")); //#else // luaEnv.AddLoader(MyLoader); // //luaEnv.DoString(string.Format("package.path = '{0}/?.bytes'", Application.persistentDataPath)); //#endif DoString("require 'Main'"); }
// Start is called before the first frame update void Start() { luaEnv = new LuaEnv(); luaEnv.DoString(luaSprit.text); //第一种,官方推荐,映射到delegate /* 注意事项 * 1.对于lua function的每一个参数就声明一个输入类型的参数(不是out,ref的) * 2.关于多值返回的处理,除第一个返回值外,其他返回值从左往右映射到C#的输出参数(out参数和ref参数) * 关于参数的类型,支持各种复杂类型,out,ref修饰的,甚至可以返回另一个delegate */ //获取lua无参函数 Action func = luaEnv.Global.Get <Action>("Log"); Add addfunc = luaEnv.Global.Get <Add>("Add"); MultipleReturn multipeReturn = luaEnv.Global.Get <MultipleReturn>("MultipleReturn"); func(); int reslut = addfunc(6, 3); Debug.Log("addfunc的返回值:" + reslut); string str; int firstReturnValue = multipeReturn("I am C#", out str); Debug.Log("multipeReturn的两个返回值:" + firstReturnValue + "和" + str); //第二种使用LuaFunction 不推荐使用效率差,使用过程都可以明显看到拆装箱 LuaFunction NoparamFunc = luaEnv.Global.Get <LuaFunction>("Log"); NoparamFunc.Call(); LuaFunction AddFunc = luaEnv.Global.Get <LuaFunction>("Add"); object[] luafunc_reslut = AddFunc.Call(3, 4); Debug.Log("用luafunction调用Add返回值:" + luafunc_reslut[0]); LuaFunction luafunc_multipeReturn = luaEnv.Global.Get <LuaFunction>("MultipleReturn"); object[] luafuc_multi_reslut = luafunc_multipeReturn.Call("i am LuaFunction"); foreach (var item in luafuc_multi_reslut) { Debug.Log(item); } //官方推荐如果lua函数不是多返回值函数,建议使用Action和Func,这两个是无CG api,也可以自己去Luafunction里面去加 Func <int, int, int> CSFunc = luaEnv.Global.Get <Func <int, int, int> >("Add"); int funcReslut; funcReslut = CSFunc(21, 22); Debug.Log("使用C# Func来接收加法结果:" + funcReslut); }
void initLua() { luaFileIsNull = false; table = luaenv.NewTable(); if (string.IsNullOrEmpty(luaString)) { if (textFile == null) { if (luaFileName == null) { Debug.Log("没有lua文件"); return; } else { luaString = Resources.Load <TextAsset>("lua/" + luaFileName).text;//TestLua.lua luaName = luaFileName.Substring(0, luaFileName.IndexOf('.')); } } else { luaString = textFile.text; luaName = textFile.name.Substring(0, textFile.name.IndexOf('.')); } } print("++++++++++++++++++++" + luaString); luaenv.DoString(luaString);//lua2.lua // Debug.Log("tableName: " + luaName); luaenv.Global.Get(luaName, out table); System.Action awake = table.Get <System.Action>("Awake"); //将数据存于lua中的table table.Set("self", this); table.Set("transform", transform); table.Get("Start", out luaStart); table.Get("Update", out luaUpdate); table.Get("OnDestroy", out luaOnDestroy); if (awake != null) { awake(); } }
void Awake() { LuaEnv luaenvScriptCtrl = luaEnv; // share Only one Lua Env; scriptEnv = luaEnv.NewTable(); LuaTable meta = luaEnv.NewTable(); meta.Set("__index", luaEnv.Global); scriptEnv.SetMetaTable(meta); meta.Dispose(); scriptEnv.Set("self", this); foreach (var injection in injections) { scriptEnv.Set(injection.name, injection.value); } LuaEnv.CustomLoader method = CustomLoaderMethod; luaenvScriptCtrl.AddLoader(method); if (xluaname == "") { xluaname = this.name; } if (chunkname == "") { chunkname = this.name; } // luaenvScriptCtrl.DoString(@"require('" + xluaname + @"')", chunkname, scriptEnv); byte[] data = CustomLoaderMethod(ref xluaname); string text = System.Text.Encoding.UTF8.GetString(data); luaEnv.DoString(text, chunkname, scriptEnv); // luaEnv.DoString(luaScript.text, "LuaTestScript", scriptEnv); Action luaAwake = scriptEnv.Get <Action>("awake"); scriptEnv.Get("start", out luaStart); scriptEnv.Get("update", out luaUpdate); scriptEnv.Get("ondestroy", out luaOnDestroy); if (luaAwake != null) { luaAwake(); } }
public void SafeDoString(string scriptContent) { if (luaEnv != null) { try { luaEnv.DoString(scriptContent); } catch (System.Exception ex) { string msg = string.Format("xLua exception : {0}\n {1}", ex.Message, ex.StackTrace); Logger.LogError(msg, null); } } }
private void Start() { LuaEnv luaenv = new LuaEnv(); luaenv.DoString(@" local RawByteArray = CS.EZUnity.XLuaExample.RawByteArray local RawObjectTest = CS.EZUnity.XLuaExample.RawObjectTest -- 直接传递byte[],lua会作为string处理,通过继承RawObject的RawByteArray,实现string以byte[]方式传递 local byteArray = RawByteArray.GetBytes('string from lua') local rawByteArray = RawByteArray('string from lua') print(RawObjectTest.GetTypeName(byteArray), byteArray) print(RawObjectTest.GetTypeName(rawByteArray), rawByteArray) "); luaenv.Dispose(); }
/// <summary> /// 热补丁开始修复中。。。 /// </summary> public void HotStartFixing() { //配置表始终从luaGloablData中读取 mLuaEnv = new LuaEnv(); LuaEnv.CustomLoader method = CustomLoaderMethod; mLuaEnv.AddLoader(method); ReadGlobalData(); if (!GameManager.Instance.mIsLuaUpdate) { return; } //这句话注释掉可以全部用lua开发 Debug.Log("Start HotFix..."); mLuaEnv.DoString("require 'Main'"); }
private void Start() { luaEnv = new LuaEnv(); /* * // 方法一 : Resources.Load<TextAsset>() 通过加载文本的方式 * // luaByFile.lua.txt 文件 , 不用加 .txt 后缀 * TextAsset ta = Resources.Load<TextAsset>("luaByFile.lua"); * luaEnv.DoString(ta.ToString()); */ // 方法二 : require '' 方式 // luaByFile.lua.txt 文件 , 不用加后缀 luaEnv.DoString("require'luaByFile'"); }
public void Import(string path) { string importPath = Path.Combine(luaPath, path); string[] luaFils = Directory.GetFiles(importPath, "*.lua", SearchOption.AllDirectories); if (luaFils != null && luaFils.Length > 0) { for (int i = 0; i < luaFils.Length; i++) { string luaFile = luaFils[i]; byte[] bytes = File.ReadAllBytes(luaFile); LuaEnv.DoString(bytes, luaFile); } } }
// Start is called before the first frame update private void Start() { env = new LuaEnv(); env.DoString("require 'CallLua'"); XLua.LuaTable gl = env.Global.Get <XLua.LuaTable>("gameUser"); Debug.Log("luatable---" + gl.Get <string>("name")); //函数 XLua.LuaFunction fun = gl.Get <XLua.LuaFunction>("Speak"); fun.Call(); XLua.LuaFunction fun1 = gl.Get <XLua.LuaFunction>("Caculation"); object[] objarray = fun1.Call(gl, 2, 3); Debug.Log("result--" + objarray[0]); }
public void Start() { if (null != luaEnv) { Debugger.Log("lua start"); luaEnv.DoString("require ('app/main')"); luaStart = luaEnv.Global.Get <Action>("Start"); luaExit = luaEnv.Global.Get <Action>("Exit"); luaUpdate = luaEnv.Global.Get <Action <float, float> >("Update"); if (null != luaStart) { luaStart(); } } }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.DoString(script); Debug.Log("_G.a = " + luaenv.Global.Get<int>("a")); Debug.Log("_G.b = " + luaenv.Global.Get<string>("b")); Debug.Log("_G.c = " + luaenv.Global.Get<bool>("c")); DClass d = luaenv.Global.Get<DClass>("d");//映射到有对应字段的class,by value Debug.Log("_G.d = {f1=" + d.f1 + ", f2=" + d.f2 + "}"); Dictionary<string, double> d1 = luaenv.Global.Get<Dictionary<string, double>>("d");//映射到Dictionary<string, double>,by value Debug.Log("_G.d = {f1=" + d1["f1"] + ", f2=" + d1["f2"] + "}, d.Count=" + d1.Count); List<double> d2 = luaenv.Global.Get<List<double>>("d"); //映射到List<double>,by value Debug.Log("_G.d.len = " + d2.Count); ItfD d3 = luaenv.Global.Get<ItfD>("d"); //映射到interface实例,by ref,这个要求interface加到生成列表,否则会返回null,建议用法 d3.f2 = 1000; Debug.Log("_G.d = {f1=" + d3.f1 + ", f2=" + d3.f2 + "}"); Debug.Log("_G.d:add(1, 2)=" + d3.add(1, 2)); LuaTable d4 = luaenv.Global.Get<LuaTable>("d");//映射到LuaTable,by ref Debug.Log("_G.d = {f1=" + d4.Get<int>("f1") + ", f2=" + d4.Get<int>("f2") + "}"); Action e = luaenv.Global.Get<Action>("e");//映射到一个delgate,要求delegate加到生成列表,否则返回null,建议用法 e(); FDelegate f = luaenv.Global.Get<FDelegate>("f"); DClass d_ret; int f_ret = f(100, "John", out d_ret);//lua的多返回值映射:从左往右映射到c#的输出参数,输出参数包括返回值,out参数,ref参数 Debug.Log("ret.d = {f1=" + d_ret.f1 + ", f2=" + d_ret.f2 + "}, ret=" + f_ret); GetE ret_e = luaenv.Global.Get<GetE>("ret_e");//delegate可以返回更复杂的类型,甚至是另外一个delegate e = ret_e(); e(); LuaFunction d_e = luaenv.Global.Get<LuaFunction>("e"); d_e.Call(); }
void Start() { luaenv = new LuaEnv(); luaenv.DoString("require 'async_test'"); }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.DoString("require 'coruntine_test'"); }
// Use this for initialization void Start() { LuaEnv luaenv = new LuaEnv(); luaenv.DoString("CS.UnityEngine.Debug.Log('hello world')"); luaenv.Dispose(); }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.DoString("print('hello world')"); }
// Use this for initialization void Start() { luaenv = new LuaEnv(); luaenv.DoString("require 'byfile'"); }
private void Start() { env = new LuaEnv(); env.DoString(script); }