static void Main2() { Lua L = new Lua(); // L.DoString("UnityEngine = luanet.UnityEngine"); // L.DoString("print(UnityEngine)"); // L.DoString("cubetype = UnityEngine.PrimitiveType.Cube"); // L.DoString("print(cubetype)"); // L.DoString("gotype = UnityEngine.GameObject"); // L.DoString("print(gotype)"); // L.DoString("CP = gotype.CreatePrimitive"); // L.DoString("print(CP)"); // L.DoString("cube2 = UnityEngine.GameObject.CP2()"); // L.DoString("print(cube2)"); // L.DoString("cube = CP(cubetype)"); // L.DoString("cube = luanet.UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube)"); L.DoString("luanet.import_type(UnityEngine.GameObject)()"); L.DoString("luanet.UnityEngine.GameObject.CP2()"); while (true) { L.DoString("t = UnityEngine.Time.realtimeSinceStartup"); L.DoString("q = UnityEngine.Quaternion.AngleAxis(t*50, UnityEngine.Vector3.up)"); L.DoString("cube.transform.rotation = q"); System.Threading.Thread.Sleep(1); } }
static void Main(string[] args) { using (var lua = new Lua()) { lua.DoFile("Apollo.lua"); var luaUnit = @"C:/git/luaunit"; var addonDir = "TrackMaster"; var addonPath = Path.Combine(Environment.GetEnvironmentVariable("appdata"), @"NCSOFT\Wildstar\Addons\" + addonDir + @"\"); lua.DoString(string.Format("package.path = package.path .. ';{0}/?.lua;{1}/?.lua'", luaUnit, addonPath.Replace('\\', '/'))); var toc = XDocument.Load(Path.Combine(addonPath, "toc.xml")); foreach (var script in toc.Element("Addon").Elements("Script")) { lua.DoFile(Path.Combine(addonPath, script.Attribute("Name").Value)); } foreach (var testFiles in Directory.GetFiles(Path.Combine(addonPath, "Tests"))) { Console.WriteLine("Loading File: " + testFiles); lua.DoFile(testFiles); } try { lua.DoString("require('luaunit'):run()"); } catch (LuaException ex) { Console.WriteLine("Execution Error: " + ex.ToString()); } //Console.ReadLine(); } }
void Start() { _lua = new Lua(); _lua.DoString("UnityEngine = luanet.UnityEngine"); _lua.DoString("System = luanet.System"); _lua["gameObject"] = this; Code = "function update(dt)\n\nend\n"; DoCode(Code); }
void Update() { if (virgin) { virgin = false; L = new Lua(); gameObject.GetComponent<Renderer>().material.color = new Color(1.0f, 0.8f, 0.2f); L.DoString("r = 0"); L.DoString("g = 1"); L.DoString("b = 0.2"); float r = (float)(double)L["r"]; float g = (float)(double)L["g"]; float b = (float)(double)L["b"]; gameObject.GetComponent<Renderer>().material.color = new Color(r, g, b); Debug.Log("1"); L["go"] = gameObject; Debug.Log("2"); Vector3 v = gameObject.transform.position; v.y += 1.0f; L["v"] = v; Debug.Log("3"); L.DoString("go.transform.position = v"); Debug.Log("4"); string[] script = { "UnityEngine = luanet.UnityEngine", "cube = UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube)", "" }; foreach (var line in script) { L.DoString(line); } } L.DoString("t = UnityEngine.Time.realtimeSinceStartup"); L.DoString("q = UnityEngine.Quaternion.AngleAxis(t*50, UnityEngine.Vector3.up)"); L.DoString("cube.transform.rotation = q"); }
static void Main(string[] args) { Lua lua = new Lua(); lua["x"] = 3; lua.DoString("y=x"); Console.WriteLine("y={0}", lua["y"]); { object[] retVals = lua.DoString("return 1,'hello'"); Console.WriteLine("{0},{1}", retVals[0], retVals[1]); } { KopiLua.Lua.lua_pushcfunction(lua.luaState, Func); KopiLua.Lua.lua_setglobal(lua.luaState, "func"); Console.WriteLine("registered 'func'"); double result = (double)lua.DoString("return func(1,2,3)")[0]; Console.WriteLine("{0}", result); } { Bar bar = new Bar(); bar.x = 2; lua["bar"] = bar; Console.WriteLine("'bar' registered"); object o = lua["bar"]; Console.WriteLine("'bar' read back as {0}", o); Console.WriteLine(o == bar ? "same" : "different"); Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]); double result = (double)lua.DoString("return bar.x")[0]; Console.WriteLine("lua says bar.x = {0}", result); lua.DoString("bar.x = 4"); Console.WriteLine("now bar.x = {0}", bar.x); } { Foo foo = new Foo(); lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply")); Console.WriteLine("registered 'multiply'"); double result = (double)lua.DoString("return multiply(3)")[0]; Console.WriteLine("{0}", result); } Console.ReadLine(); }
void Start() { Debug.Log("== 测试 == C#获取Lua Float"); Lua lua = new Lua(); lua.DoString("num1 = -0.9999999"); Debug.Log(lua["num1"]); }
static void Main(string[] args) { LuaInterface.Lua lua = new LuaInterface.Lua(); lua.DoString("print('12345')"); lua.DoFile("test.lua"); Console.WriteLine((string)lua["str"]);//访问lua中的变量 Program p = new Program(); lua.RegisterFunction("NormalMethod", p, p.GetType().GetMethod("Method")); lua.DoString("NormalMethod()"); lua.RegisterFunction("StaticMethod", null, typeof(Program).GetMethod("StaticMethod")); lua.DoString("StaticMethod()"); lua.DoFile("go.lua"); Console.ReadKey(); }
public void Run(string input) { try { Lua.DoString(input); } catch (Exception e) { Program.Write(e.ToString()); } }
public void Load(Lua lua) { if(lua == null) { return; } foreach(TextAsset code in Scripts) { lua.DoString(code.text); } }
private static void Main(string[] args) { using (Lua = new Lua()) { Lua["_TESTRUNNER"] = true; Lua.DoFile("Apollo.lua"); Lua.DoString("function Print(string) print(string) end"); Lua.RegisterFunction("XmlDoc.CreateFromFile", null, typeof(XmlDoc).GetMethod("CreateFromFile")); string addonDir = "TrackMaster"; string addonPath = FindTocFile(args.FirstOrDefault()) ?? Path.Combine(Environment.GetEnvironmentVariable("appdata"), @"NCSOFT\Wildstar\Addons\" + addonDir + @"\"); Directory.SetCurrentDirectory(addonPath); Lua.DoString(string.Format("package.path = package.path .. ';{0}/?.lua'", addonPath.Replace('\\', '/'))); XDocument toc = XDocument.Load(Path.Combine(addonPath, "toc.xml")); Lua.DoString(string.Format("Apollo.__AddonName = '{0}'", toc.Element("Addon").Attribute("Name").Value)); foreach (XElement script in toc.Element("Addon").Elements("Script")) { Console.WriteLine("Loading File: " + script.Attribute("Name").Value); Lua.DoFile(Path.Combine(addonPath, script.Attribute("Name").Value)); } //foreach (var testFiles in Directory.GetFiles(Path.Combine(addonPath, "Tests"))) //{ // Console.WriteLine("Loading File: " + testFiles); // Lua.DoFile(testFiles); //} try { //Lua.DoString("Apollo.GetPackage('WildstarUT-1.0').tPackage:RunAllTests()"); Lua.DoString("Apollo.GetPackage('Lib:Busted-2.0').tPackage:RunAllTests()"); } catch (LuaException ex) { Console.WriteLine("Execution Error: " + ex); } } }
static void Main(string[] args) { Lua lua = new Lua(); lua["x"] = 3; lua.DoString("y=x"); Console.WriteLine("y={0}", lua["y"]); { lua.DoString("luanet.load_assembly('SimpleTest')"); lua.DoString("Foo = luanet.import_type('SimpleTest.Foo')"); lua.DoString("method = luanet.get_method_bysig(Foo, 'OutMethod', 'SimpleTest.Foo', 'out SimpleTest.Bar')"); Console.WriteLine(lua["method"]); } { object[] retVals = lua.DoString("return 1,'hello'"); Console.WriteLine("{0},{1}", retVals[0], retVals[1]); } { KopiLua.Lua.lua_pushcfunction(lua.luaState, Func); KopiLua.Lua.lua_setglobal(lua.luaState, "func"); Console.WriteLine("registered 'func'"); double result = (double)lua.DoString("return func(1,2,3)")[0]; Console.WriteLine("{0}", result); } { Bar bar = new Bar(); bar.x = 2; lua["bar"] = bar; Console.WriteLine("'bar' registered"); object o = lua["bar"]; Console.WriteLine("'bar' read back as {0}", o); Console.WriteLine(o == bar ? "same" : "different"); Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]); double result = (double)lua.DoString("return bar.x")[0]; Console.WriteLine("lua says bar.x = {0}", result); lua.DoString("bar.x = 4"); Console.WriteLine("now bar.x = {0}", bar.x); } { Foo foo = new Foo(); lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply")); Console.WriteLine("registered 'multiply'"); double result = (double)lua.DoString("return multiply(3)")[0]; Console.WriteLine("{0}", result); } Console.WriteLine("Finished, press Enter to quit"); Console.ReadLine(); }
public void DoFile(Stream stream) { try { StreamReader sr = new StreamReader(stream); String buffer = sr.ReadToEnd(); m_luaState.DoString(buffer); } catch (Exception e) { Engine.Log.Error(">>A .Net Exception occurred:"); Engine.Log.Error(">>" + e.Message); throw e; } }
public void Initialize() { _lua = new Lua(); if(PreLoad != null) { PreLoad.Load(_lua); } SetData(); foreach(TextAsset code in Scripts) { _lua.DoString(code.text); } }
void Start() { L = new Lua(); L.DoString(luaText.text); object[] v; v = L.GetFunction("getCostStaminaByLevel").Call(4,4); dumpResult("getCostStaminaByLevel",v); // v = L.GetFunction("rewardGold").Call(4,4,21); dumpResult("rewardGold",v); // v = L.GetFunction("getGearLevelUpCostSilver").Call(1,2,100,100); dumpResult("getGearLevelUpCostSilver",v); // v = L.GetFunction("getPracticeLimitAtk").Call(4); // dumpResult("getPracticeLimitAtk",v); // v = L.GetFunction("getPracticeLimitDef").Call(4); // dumpResult("getPracticeLimitDef",v); // v = L.GetFunction("getPracticeLimitSp").Call(5); // dumpResult("getPracticeLimitSp",v); // v = L.GetFunction("getSummonCostCash").Call("b"); // dumpResult("getSummonCostCash",v); // // // // v = L.GetFunction("getTrumpFuseProvideXp").Call(4,2); // dumpResult("getTrumpFuseProvideXp",v); // // v = L.GetFunction("getEquipForgeLvLimit").Call(3); // dumpResult("getEquipForgeLvLimit",v); // // v = L.GetFunction("getEquipForgeCostCoins").Call(2,11); // dumpResult("getEquipForgeCostCoins",v); // // v = L.GetFunction("getEquipForgeCostEquipClips").Call(2); // dumpResult("getEquipForgeCostEquipClips",v); // // v = L.GetFunction("getPracticeLimitHp").Call(2); // dumpResult("getPracticeLimitHp",v); // v = L.GetFunction("getPracticeLimitAtk").Call(2); // dumpResult("getPracticeLimitAtk",v); // v = L.GetFunction("getPracticeLimitDef").Call(2); // dumpResult("getPracticeLimitDef",v); // v = L.GetFunction("getPracticeLimitSp").Call(2); // dumpResult("getPracticeLimitSp",v); }
public LuaFunction boundMessageFunction; //Reference to bound Lua function set within Lua // Constructor public LuaAPI() { // create new instance of Lua lua = new Lua(); // Initialize array. movementQueue = new Queue(); // Get the UnityEngine reference lua.DoString("UnityEngine = luanet.UnityEngine"); // get the boat and its controls boat = GameObject.FindGameObjectWithTag("TheBoat"); shipControls = boat.GetComponent<ShipControls>(); //Tell Lua about the LuaBinding object to allow Lua to call C# functions lua["luabinding"] = this; //Run the code contained within the file lua.DoFile(Application.streamingAssetsPath + "/" + drivers); }
public static void read (Lua L) { using (System.IO.StreamReader sr = System.IO.File.OpenText(fullLuaPath)) { string line; //while the reader is not at the end of text. load a lua line. while ((line = sr.ReadLine()) != null) { luaLines.Add(line); L.DoString(line); GDLog.log(line); } } luaLines.Clear(); using (System.IO.StreamWriter sw = System.IO.File.CreateText(fullLuaPath)) { //only here to create the file and close the stream //if it ain't broke don't fix it GDLog.log("Erasing path for lua logger"); } }
private void InitLua() { try { m_lua = new Lua(); m_lua["MainForm"] = (MainForm)ParentForm; m_lua["SkillForm"] = this; //m_lua["oo"] = new tcls1(); //建立环境帮助函数 m_lua.DoString("function trace() \r\n end\r\n"); string sCode = "____main_env_varTable = {}\r\nlocal function _MakeEnv(envname)\r\n ____main_env_varTable[envname] = {}\r\n _G[\"__fname__\"..envname] = ____main_env_varTable[envname]\r\n____main_env_varTable[envname].envname = envname\r\n setmetatable(____main_env_varTable[envname], {__index = _G})\r\nend\r\nfunction _ChgEnv(envname)\r\n if (envname == nil) then\r\n setfenv(2, _G)\r\n elseif (____main_env_varTable[envname] == nil) then\r\n _MakeEnv(envname)\r\n setfenv(2, ____main_env_varTable[envname])\r\n else\r\n setfenv(2, ____main_env_varTable[envname])\r\n end\r\nend\r\n"; m_lua.DoString(sCode); m_lua.RegisterFunction("ClearTreeNodes", this, typeof(SkillForm).GetMethod("ClearTreeNodes")); m_lua.RegisterFunction("AddTreeNodes", this, typeof(SkillForm).GetMethod("AddTreeNodes")); m_lua.RegisterFunction("SqlQueryOnce", this, typeof(SkillForm).GetMethod("SqlQueryOnce")); m_lua.RegisterFunction("SqlInsertLevelRecord", this, typeof(SkillForm).GetMethod("SqlInsertLevelRecord")); m_lua.RegisterFunction("SqlSetPrimKey", this, typeof(SkillForm).GetMethod("SqlSetPrimKey")); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static void Main(string[] args) { Console.WriteLine("Hellow Lua"); #region 使用C#写lua,并在lua虚拟机中执行 ---字段属性篇 // 第一种 : 创建lua虚拟机的形式直接写lua Lua lua = new Lua(); // 创建lua虚拟机(lua解析器) lua["m_Age"] = 23; lua["m_PlayerName"] = "胖儿子"; lua.NewTable("m_HeroTable"); Console.WriteLine(lua["m_Age"] + "----" + lua["m_PlayerName"]); // C#和lua中变量对应参考: // nil ------ null // string ------ System.String // number ------ System.Double // boolean ------ System.Boolean // table ------ LuaInterface.LuaTable // function ------ LuaInterface.LuaFunction double age = (double)lua["m_Age"]; string name = (string)lua["m_PlayerName"]; Console.WriteLine(age + "---" + name); // 第二种 : 使用lua.DoString() 编写Lua lua.DoString("account = 20170504"); lua.DoString("str = 'youga'"); object[] result = lua.DoString("return str, account"); foreach (object item in result) { Console.WriteLine(item); } // 第三种: lua.DoFile() 编写Lua //1. 解决方案 - 右击 LuaInterface(项目名) - 添加 - 新建项 - 建一个名为LuaTest.lua的类 //2. 把lua代码放进去,把编码格式改为ANSI(可以用Notepad++) //3. 右击LuaTest.lua - 属性 - 复制到输出目录 - 选择始终复制即可 lua.DoFile("LuaTest.lua"); #endregion #region 使用C#写lua,并在lua虚拟机中执行 ---方法篇 //1. 将一个类里面的普通方法注册进lua中并执行 TestClass t = new TestClass(); // 注意: 普通方法一定要注明是哪个对象 lua.RegisterFunction("MyNormalCLRMethod", t, t.GetType().GetMethod("MyNormalCLRMethod")); lua.DoString("MyNormalCLRMethod()"); // 如果是开发时一般名字要保持一致,这里只是为了演示C#代码给lua执行的意思 //2. 将一个类里面的静态方法注册进Lua中并执行 lua.RegisterFunction("MyStaticCLRMethod", null, typeof(TestClass).GetMethod("MyStaticCLRMethod")); lua.DoString("MyStaticCLRMethod()"); #endregion Console.ReadKey(); lua.Dispose(); }
private void testScript_Click(object sender, EventArgs e) { Lua lua = new Lua(); lua.RegisterMarkedMethodsOf(this); //add some variables so we can pass tests lua["item"] = Items.ItemFactory.CreateItem(ObjectId.Parse("5383dc8531b6bd11c4095993")); if (byPassTestValue.Visible) { ScriptError = !byPassTestValue.Checked; } else { try { lua.DoString(scriptValue.Text); ScriptError = false; scriptValidatedValue.Visible = true; } catch (LuaException lex) { MessageBox.Show(lex.Message, "Lua Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ScriptError = true; scriptValidatedValue.Visible = false; } } }
/// <summary> /// /// </summary> /// <param name="chunk"></param> /// <returns></returns> public object[] DoString(string chunk) { return(_lua.DoString(chunk)); }
private void testScript_Click(object sender, EventArgs e) { scriptValidatedValue.Visible = false; if (scriptTypeValue.Text == "Lua") { Lua lua = new Lua(); lua.RegisterMarkedMethodsOf(this); //add some variables so we can pass tests lua["item"] = Items.ItemFactory.CreateItem(ObjectId.Parse("5383dc8531b6bd11c4095993")); if (byPassTestValue.Visible) { ScriptError = !byPassTestValue.Checked; } else { try { lua.DoString(scriptValue.Text); ScriptError = false; scriptValidatedValue.Visible = true; } catch (LuaException lex) { MessageBox.Show(lex.Message, "Lua Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ScriptError = true; } } } else { if (byPassTestValue.Visible) { ScriptError = !byPassTestValue.Checked; } ScriptEngine engine = new ScriptEngine(); ScriptMethods host = new ScriptMethods(); host.DataSet.Add("player", Character.NPCUtils.CreateNPC(1)); host.DataSet.Add("npc", Character.NPCUtils.CreateNPC(1)); Roslyn.Scripting.Session session = engine.CreateSession(host, host.GetType()); new[] { typeof (Type).Assembly, typeof (ICollection).Assembly, typeof (Console).Assembly, typeof (RoslynScript).Assembly, typeof (IEnumerable<>).Assembly, typeof (IQueryable).Assembly, typeof (ScriptMethods).Assembly, typeof(IActor).Assembly, typeof(Character.Character).Assembly, typeof(NPC).Assembly, typeof(Room).Assembly, typeof(Commands.CommandParser).Assembly, typeof(Interfaces.Message).Assembly, GetType().Assembly }.ToList().ForEach(asm => session.AddReference(asm)); //Import common namespaces new[] { "System", "System.Linq", "System.Object", "System.Collections", "System.Collections.Generic", "System.Text", "System.Threading.Tasks", "System.IO", "Character", "Rooms", "Items", "Commands", "ClientHandling", "Triggers" }.ToList().ForEach(ns => session.ImportNamespace(ns)); try { var result = session.CompileSubmission<object>(scriptValue.Text); ScriptError = false; scriptValidatedValue.Visible = true; } catch (Exception ex) { MessageBox.Show("Errors found in script:\n " + ex.Message, "Script Errors", MessageBoxButtons.OK); } } }
/// <summary> /// Doc: http://stackoverflow.com/questions/14299634/luainterface-a-function-which-will-return-a-luatable-value /// </summary> /// <param name="list"></param> /// <param name="lua"></param> /// <returns></returns> private static LuaTable ToLuaTable(List<String> list, Lua lua) { StringBuilder sb = new StringBuilder(); sb.Append("return {"); bool first = true; int index = 1; foreach (String value in list) { if (!first) sb.Append(", "); sb.Append("["); sb.Append(index); sb.Append("] = \""); sb.Append(value.Replace("\"", "\\\"")); sb.Append("\"\n "); if (first) first = false; ++index; } sb.Append("} \n"); LuaTable table = (LuaTable)lua.DoString(sb.ToString())[0]; return table; }
public void Run() { Lua lua = new Lua(); try { lua.DoFile(m_strExecFile); } catch (Exception Ex) { Console.WriteLine(Ex.Message); return; } LuaTable luaTable = lua.GetTable("EVENT_LIST"); foreach (object Key in luaTable.Keys) { string strEventFunction = (string)luaTable[Key]; //整理参数格式为 “param1, param2, param3, ” int nIndexP = strEventFunction.IndexOf("(") + 1; int nIndexE = strEventFunction.IndexOf(")"); string strFunctionName = strEventFunction.Substring(0, nIndexP - 1); string strParam = strEventFunction.Substring(nIndexP, nIndexE - nIndexP) + ", "; nIndexP = 0; nIndexE = 0; strFunctionName = strFunctionName + "("; while (true) { nIndexP = nIndexE; nIndexE = strParam.IndexOf(", ", nIndexP) + 2; if (nIndexE == 1) { break; } string strParamName = strParam.Substring(nIndexP, nIndexE - 2 - nIndexP); string sb = GetStringFromFile("GetParam", strParamName, "nil"); if (sb == "nil") { MessageBox.Show("配置文件中无法找到逻辑检查代入参数:" + strParamName); } strFunctionName = strFunctionName + sb + ", "; } if (strEventFunction.IndexOf("(") + 1 != strEventFunction.IndexOf(")")) { strFunctionName = strFunctionName.Substring(0, strFunctionName.Length - 2); } strFunctionName = strFunctionName + ")"; try { lua.DoString(strFunctionName); } catch (Exception Ex) { //过滤因为调用了不存在的Event引起的错误 string strFunc = strFunctionName.Substring(0, strFunctionName.IndexOf("(")); int nIndexEx = Ex.Message.IndexOf(strFunc); if (nIndexEx == -1) { Console.WriteLine(Ex.Message); } } } }
/// <summary> /// 新建文件 /// </summary> /// <param name="sender">事件发送者</param> /// <param name="e">事件参数</param> private void cmdTreePhFolder_newFile_Click(object sender, EventArgs e) { if (treePh.SelectedNode != null) { // 开始和lua交互 string strFullPath = treePh.SelectedNode.FullPath; Lua plua = new Lua(); object[] oRet = null; plua.DoString(DataBaseManager.GetDataBaseManager().GetScriptData(this.getFileIDsFromPath("Template")[0].ToString())); LuaFunction fun = plua.GetFunction("LoadParms"); if (fun != null) { object[] args = { strFullPath }; oRet = fun.Call(args); if (oRet == null) { return; } } string strControls = oRet[0] as string; // 孙韬返回的内容 object[] strParms; // 文件名 string strName = ""; string[] asp1 = { "|" }; ModelForm mf = new ModelForm(strControls.Split(asp1, StringSplitOptions.RemoveEmptyEntries)); if (mf.ShowDialog() == DialogResult.OK) { List<string> list = mf.InputList; if (list.Count >= 2) { strParms = list.ToArray(); strName = strParms[1] as string; string strCode = ""; fun = plua.GetFunction("LoadScript"); if (fun != null) { oRet = fun.Call(strParms); strCode = oRet[0] as string; } else { return; } // 交互完毕 if (string.IsNullOrEmpty(strName)) { return; } if (CheckNodeExist(treePh.SelectedNode, strName)) { MessageBox.Show("当前树结点已经存在!", "新建文件", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Hashtable infoTable = new Hashtable(); infoTable["type"] = "file"; // 存数据库 DataBaseManager dbm = DataBaseManager.GetDataBaseManager(); string strPath = treePh.SelectedNode.FullPath; string[] asp = { "\\" }; string[] as_Path = strPath.Split(asp, StringSplitOptions.RemoveEmptyEntries); if (as_Path.Length < 2 && as_Path[0] == "scripts") { MessageBox.Show("暂时不支持在其他地图以外的目录建文件", "新建文件", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string id = dbm.CreateScriptData(string.Format("{0}\\{1}", strPath, strName)); if (id == null) { MessageBox.Show("新建文件失败!", "新建文件", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { // 新建成功,更新树缓存 treePh.Tag = dbm.GetScriptInformation(); } infoTable["id"] = id; infoTable["scriptType"] = "databaseFile"; TreeNode newNode = treePh.SelectedNode.Nodes.Add(strName, strName); newNode.ImageKey = "file"; newNode.SelectedImageKey = "file"; newNode.Tag = infoTable; newNode.ContextMenuStrip = this.popTreePh_File; treePh.SelectedNode.Expand(); treePh.SelectedNode = newNode; // 模拟点击节点 this.treePh_NodeMouseDoubleClick(this, new TreeNodeMouseClickEventArgs(newNode, MouseButtons.Left, 2, 1, 1)); EditForm fe = this.ActiveMdiChild as EditForm; // 模板内容写入 if (fe != null) { fe.luaEditBox.Text = strCode; } } } } }
static void Main(string[] args) { var lua = new Lua(); Console.WriteLine("LuaTable disposal stress test..."); { lua.DoString("a={b={c=0}}"); for (var i = 0; i < 100000; ++i) { // Note that we don't even need the object type to be LuaTable - c is an int. // Simply indexing through tables in the string expression was enough to cause // the bug... var z = lua["a.b.c"]; } } Console.WriteLine(" ... passed"); Console.WriteLine("LuaFunction disposal stress test..."); { lua.DoString("function func() return func end"); for (var i = 0; i < 100000; ++i) { var f = lua["func"]; } } Console.WriteLine(" ... passed"); lua["x"] = 3; lua.DoString("y=x"); Console.WriteLine("y={0}", lua["y"]); { lua.DoString("luanet.load_assembly('SimpleTest')"); lua.DoString("Foo = luanet.import_type('SimpleTest.Foo')"); lua.DoString("method = luanet.get_method_bysig(Foo, 'OutMethod', 'SimpleTest.Foo', 'out SimpleTest.Bar')"); Console.WriteLine(lua["method"]); } { object[] retVals = lua.DoString("return 1,'hello'"); Console.WriteLine("{0},{1}", retVals[0], retVals[1]); } { KopiLua.Lua.lua_pushcfunction(lua.luaState, Func); KopiLua.Lua.lua_setglobal(lua.luaState, "func"); Console.WriteLine("registered 'func'"); double result = (double)lua.DoString("return func(1,2,3)")[0]; Console.WriteLine("{0}", result); } { Bar bar = new Bar(); bar.x = 2; lua["bar"] = bar; Console.WriteLine("'bar' registered"); object o = lua["bar"]; Console.WriteLine("'bar' read back as {0}", o); Console.WriteLine(o == bar ? "same" : "different"); Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]); double result = (double)lua.DoString("return bar.x")[0]; Console.WriteLine("lua says bar.x = {0}", result); lua.DoString("bar.x = 4"); Console.WriteLine("now bar.x = {0}", bar.x); } { Foo foo = new Foo(); lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply")); Console.WriteLine("registered 'multiply'"); double result = (double)lua.DoString("return multiply(3)")[0]; Console.WriteLine("{0}", result); } Console.WriteLine("Finished, press Enter to quit"); Console.ReadLine(); }
public static void Main(string[] args) { Lua L = new Lua(); // testing out parameters and type coercion for object[] args. L["obj"] = new RefParms(); dump("void,out,out",L.DoString("return obj:Args()")); dump("int,out,out",L.DoString("return obj:ArgsI()")); L.DoString("obj:ArgsVar{1}"); Console.WriteLine("equals {0} {1} {2}",IsInteger(2.3),IsInteger(0),IsInteger(44)); //Environment.Exit(0); object[] res = L.DoString("return 20,'hello'","tmp"); Console.WriteLine("returned {0} {1}",res[0],res[1]); L.DoString("answer = 42"); Console.WriteLine("answer was {0}",L["answer"]); MyClass.Register(L); L.DoString(@" print(Sqr(4)) print(Sum(1.2,10)) -- please note that this isn't true varargs syntax! print(utils.sum {1,5,4.2}) "); L.DoString("X = {1,2,3}; Y = {fred='dog',alice='cat'}"); LuaTable X = (LuaTable)L["X"]; Console.WriteLine("1st {0} 2nd {1}",X[1],X[2]); // (but no Length defined: an oversight?) Console.WriteLine("X[4] was nil {0}",X[4] == null); // only do this if the table only has string keys LuaTable Y = (LuaTable)L["Y"]; foreach (string s in Y.Keys) Console.WriteLine("{0}={1}",s,Y[s]); // getting and calling functions by name LuaFunction f = L.GetFunction("string.gsub"); object[] ans = f.Call("here is the dog's dog","dog","cat"); Console.WriteLine("results '{0}' {1}",ans[0],ans[1]); // and it's entirely possible to do these things from Lua... L["L"] = L; L.DoString(@" L:DoString 'print(1,2,3)' "); // it is also possible to override a CLR class in Lua using luanet.make_object. // This defines a proxy object which will successfully fool any C# code // receiving it. object[] R = L.DoString(@" luanet.load_assembly 'CallLua' -- load this program local CSharp = luanet.import_type 'CSharp' local T = {} function T:MyMethod(s) return s:lower() end function T:Protected(s) return s:upper() end function T:ProtectedBool() return true end luanet.make_object(T,'CSharp') print(CSharp.UseMe(T,'CoOl')) io.flush() return T "); // but it's still a table, and there's no way to cast it to CSharp from here... Console.WriteLine("type of returned value {0}",R[0].GetType()); }
protected override void OnLoad(EventArgs e) { lua = new Lua(); lua.DoString("luanet=nil"); Skin.luaInit(); /* Type ty = typeof(Config); foreach (MethodInfo mi in ty.GetMethods()) { lua.RegisterFunction(mi.Name,this , mi); Console.WriteLine(mi.Name); }*/ conn = new Client.Connection(); conn.recvPacket += new Action<short, Client.RecievePacket>(conn_recvPacket); Pulse.Client.PacketWriter.sendCheckVersion(conn.Bw); this.Closing += new EventHandler<System.ComponentModel.CancelEventArgs>(Game_Closing); base.OnLoad(e); AudioManager.initBass(); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); if (Skin.MaskBursts) { Animation preloadBursts = new Animation(new Rectangle(1, 1, 1, 1), 1, "burst", 10, false, true); } blackOverlay.Colour = new Color4(0.0f, 0.0f, 0.0f, 0.2f); toasts = new Queue<toast>(); toasttexture = new Rect(new Rectangle(0, 0, Config.ResWidth, 50), Skin.skindict["toast"]); volumeTexture = new Rect(new Rectangle((int)(Config.ResWidth * 0.26), 727, (int)(Config.ResWidth * 0.5), 43), Skin.skindict["volumecontrol"]); int toSet = (int)((Config.Volume / 100d) * (Config.ResWidth * 0.5)); volumeRect = new Rect(new Rectangle((int)(Config.ResWidth * 0.37), 739, toSet, 25)); volumeRect.Colour = Color4.Orange; t = new Text(new Size(Width, Height), new Size(Config.ResWidth, 50), new Point(50, 0)); this.Icon = DefaultSkin.pulseicon; SongLibrary.loadSongInfo(); SongLibrary.cacheSongInfo(); //for newly added songs while game wasn't onint diff = 0; m = new MediaPlayer(this); screens.Add("menuScreen", new MenuScreen(this, "Pulse Menu")); screens.Add("selectScreen", new SelectScreen(this, "Song Select")); screens.Add("sSScreen", new ScoreSelectScreen(this, "Score Select Screen")); screens.Add("editScreen", new EditorScreen(this, "Edit Mode")); screens.Add("timingScreen", new TimingScreen(this, "Timing Screen")); screens.Add("ingameScreen", new IngameScreen(this, "ingame")); screens["ingameScreen"].Hide(); screens["timingScreen"].Hide(); screens["editScreen"].Hide(); screens["selectScreen"].Hide(); screens["sSScreen"].Hide(); screens["menuScreen"].Show(); Active = screens["menuScreen"]; GL.ClearColor(Color4.SlateGray); fpsText = new Text(new Size(Width, Height), new Size(150, 35), new Point(Config.ResWidth - 120, 733)); fpsText.Update("fps: " + this.TargetRenderFrequency); fpsText.Colour = Color.Yellow; fpsText.Shadow = true; int tipIndex = new Random().Next(Tips.tips.Length); addToast(Tips.tips[tipIndex]); if (!Directory.Exists("skin")) { Directory.CreateDirectory("skin"); } fsw = new FileSystemWatcher("skin"); fsw.EnableRaisingEvents = true; fsw.Created += new FileSystemEventHandler(fsw_Created); pbox = new PTextBox(game, new Rectangle(0, 768 - 300, Utils.getMX(1024), 290), "", ircl); pbox.minimize(0); // Thread check = new Thread(new ThreadStart(game.checkVersions)); // check.IsBackground = true; // check.Start(); Account.tryLoadAcc(); int x = 5; SongLibrary.findByMD5(" ", ref x); userScreen = new UserDisplayScreen(this); // n = new Notice(new Point(0, 200), 5000, "ASHASHASHASHASHASHASHASHASHASHASHASHASHASHASHASDFK;J"); }
/// <summary> /// Wraps an object to prepare it for passing to LuaInterface. If no name is specified, a /// random one with the default length is used. /// </summary> public static object WrapObject(object toWrap, Lua state, string name = null) { if (toWrap is MulticastDelegate) { //We have to deal with a problem here: RegisterFunction does not really create //a new function, but a userdata with a __call metamethod. This works fine in all //except two cases: When Lua looks for an __index or __newindex metafunction and finds //a table or userdata, Lua tries to redirect the read/write operation to that table/userdata. //In case of our function that is in reality a userdata this fails. So we have to check //for these function and create a very thin wrapper arround this to make Lua see a function instead //the real userdata. This is no problem for the other metamethods, these are called independent //from their type. (If they are not nil ;)) MulticastDelegate function = (toWrap as MulticastDelegate); if (name != null && (name.EndsWith("__index") || name.EndsWith("__newindex"))) { string tmpName = LuaHelper.GetRandomString(); state.RegisterFunction(tmpName, function.Target, function.Method); state.DoString(String.Format("function {0}(...) return {1}(...) end", name, tmpName), "DynamicLua internal operation"); } else { if (name == null) name = LuaHelper.GetRandomString(); state.RegisterFunction(name, function.Target, function.Method); } return null; } else if (toWrap is DynamicLuaTable) { dynamic dlt = toWrap as DynamicLuaTable; return (LuaTable)dlt; } else return toWrap; }
/* * Sample test script that shows some of the capabilities of * LuaInterface */ public static void Main() { Console.WriteLine("Starting interpreter..."); Lua l=new Lua(); Console.WriteLine("Reading test.lua file..."); l.DoFile("test.lua"); double width=l.GetNumber("width"); double height=l.GetNumber("height"); string message=l.GetString("message"); double color_r=l.GetNumber("color.r"); double color_g=l.GetNumber("color.g"); double color_b=l.GetNumber("color.b"); Console.WriteLine("Printing values of global variables width, height and message..."); Console.WriteLine("width: "+width); Console.WriteLine("height: "+height); Console.WriteLine("message: "+message); Console.WriteLine("Printing values of the 'color' table's fields..."); Console.WriteLine("color.r: "+color_r); Console.WriteLine("color.g: "+color_g); Console.WriteLine("color.b: "+color_b); width=150; Console.WriteLine("Changing width's value and calling Lua function print to show it..."); l["width"]=width; l.GetFunction("print").Call(width); message="LuaNet Interface Test"; Console.WriteLine("Changing message's value and calling Lua function print to show it..."); l["message"]=message; l.GetFunction("print").Call(message); color_r=30; color_g=10; color_b=200; Console.WriteLine("Changing color's fields' values and calling Lua function print to show it..."); l["color.r"]=color_r; l["color.g"]=color_g; l["color.b"]=color_b; l.DoString("print(color.r,color.g,color.b)"); Console.WriteLine("Printing values of the tree table's fields..."); double leaf1=l.GetNumber("tree.branch1.leaf1"); string leaf2=l.GetString("tree.branch1.leaf2"); string leaf3=l.GetString("tree.leaf3"); Console.WriteLine("leaf1: "+leaf1); Console.WriteLine("leaf2: "+leaf2); Console.WriteLine("leaf3: "+leaf3); leaf1=30; leaf2="new leaf2"; Console.WriteLine("Changing tree's fields' values and calling Lua function print to show it..."); l["tree.branch1.leaf1"]=leaf1; l["tree.branch1.leaf2"]=leaf2; l.DoString("print(tree.branch1.leaf1,tree.branch1.leaf2)"); Console.WriteLine("Returning values from Lua with 'return'..."); object[] vals=l.DoString("return 2,3"); Console.WriteLine("Returned: "+vals[0]+" and "+vals[1]); Console.WriteLine("Calling a Lua function that returns multiple values..."); object[] vals1=l.GetFunction("func").Call(2,3); Console.WriteLine("Returned: "+vals1[0]+" and "+vals1[1]); Console.WriteLine("Creating a table and filling it from C#..."); l.NewTable("tab"); l.NewTable("tab.tab"); l["tab.a"]="a!"; l["tab.b"]=5.5; l["tab.tab.c"]=6.5; l.DoString("print(tab.a,tab.b,tab.tab.c)"); Console.WriteLine("Setting a table as another table's field..."); l["tab.a"]=l["tab.tab"]; l.DoString("print(tab.a.c)"); Console.WriteLine("Registering a C# static method and calling it from Lua..."); // Pause so we can connect with the debugger // Thread.Sleep(30000); l.RegisterFunction("func1",null,typeof(TestLuaInterface).GetMethod("func")); vals1=l.GetFunction("func1").Call(2,3); Console.WriteLine("Returned: "+vals1[0]); TestLuaInterface obj=new TestLuaInterface(); Console.WriteLine("Registering a C# instance method and calling it from Lua..."); l.RegisterFunction("func2",obj,typeof(TestLuaInterface).GetMethod("funcInstance")); vals1=l.GetFunction("func2").Call(2,3); Console.WriteLine("Returned: "+vals1[0]); Console.WriteLine("Testing throwing an exception..."); obj.ThrowUncaughtException(); Console.WriteLine("Testing catching an exception..."); obj.ThrowException(); Console.WriteLine("Testing inheriting a method from Lua..."); obj.LuaTableInheritedMethod(); Console.WriteLine("Testing overriding a C# method with Lua..."); obj.LuaTableOverridedMethod(); Console.WriteLine("Stress test RegisterFunction (based on a reported bug).."); obj.RegisterFunctionStressTest(); Console.WriteLine("Test structures..."); obj.TestStructs(); Console.WriteLine("Test Nullable types..."); obj.TestNullable(); Console.WriteLine("Test functions..."); obj.TestFunctions(); Console.WriteLine("Test event exceptions..."); obj.TestEventException(); }
// Update is called once per frame void Update() { if (request != null) { string lua = request, result; request = null; if (L == null) { L = LuaMonoBehaviour.L; L.DoString("require 'interp'"); collect_print = (LuaFunction)L["collect_print"]; } try { L.DoString(lua); object[] res = collect_print.Call (); result = (string)res[0]; } catch(System.Exception e) { result = e.Message; //collect_print.Call (); } Write (result); } }
void Start () { Debug.Log("========= Error Handle Test ========"); lua = new Lua(); string luaScript = @" -- UnityEngine UnityEngine = luanet.UnityEngine Debug = UnityEngine.Debug GameObject = UnityEngine.GameObject -- 自定义类导入 luanet.load_assembly('Assembly-CSharp') GlobalVar = luanet.GlobalVar Extentions = luanet.Extentions local Character local lbBindPower function Test() { Debug.Log('Hello'); } "; try { lua.DoString("local x = 0"); lua.DoString("local y = 1"); //lua.DoString(luaScript); } catch(KopiLua.Lua.LuaException e) { if (e.c.status == KopiLua.Lua.LUA_ERRSYNTAX) { Debug.Log( "Syntax error." + "\n\n"); } else if (e.c.status == KopiLua.Lua.LUA_ERRRUN) { Debug.Log( "LUA_ERRRUN" + "\n\n"); } else if (e.c.status == KopiLua.Lua.LUA_ERRMEM) { Debug.Log( "LUA_ERRMEM" + "\n\n"); } else if (e.c.status == KopiLua.Lua.LUA_ERRERR) { Debug.Log( "Error in error handling." + "\n\n"); } Debug.Log("HelpLink: " + e.HelpLink); Debug.Log("Message: " + e.Message); Debug.Log("Source: " + e.Source); Debug.Log("StackTrace: " + e.StackTrace); //lua.DoString("err = debug.traceback()"); //string output = lua.GetString("err"); object[] returnValues = lua.DoString("return debug.traceback()"); foreach (object o in returnValues) Debug.Log(o); } Debug.Log("========= Error Handle Test End ========"); }
public static void initLoadLuaFile(string s) { L = new Lua (); L.DoString (s); }
public void ExecuteString(string command) { _currThread = _lua.NewThread(); _currThread.DoString(command); }
/// <summary> /// Doc: http://stackoverflow.com/questions/14299634/luainterface-a-function-which-will-return-a-luatable-value /// </summary> /// <param name="dict"></param> /// <param name="lua"></param> /// <returns></returns> private static LuaTable ToLuaTable(Dictionary<String, String> dict, Lua lua) { StringBuilder sb = new StringBuilder(); sb.Append("return {"); bool first = true; foreach (KeyValuePair<String, String> keyValue in dict) { if (!first) sb.Append(", "); sb.Append("[\""); sb.Append(keyValue.Key.Replace("\"", "\\\"")); sb.Append("\"] = \""); sb.Append(keyValue.Value.Replace("\"", "\\\"")); sb.Append("\""); if (first) first = false; } sb.Append("} \n"); LuaTable table = (LuaTable)lua.DoString(sb.ToString())[0]; return table; }