Beispiel #1
0
        private static void InitEditorState(Lua state)
        {
            state.LoadCLRPackage();

            string resName = "WorldSmith.Scripts.WorldsmithImports.lua";

            Assembly asm = Assembly.GetExecutingAssembly();
            using (System.IO.Stream s = asm.GetManifestResourceStream(resName))
            using (System.IO.StreamReader reader = new System.IO.StreamReader(s))
            {
                string data = reader.ReadToEnd();

                state.DoString(data, resName);               
            }

            state["Units"] = DotaData.AllUnits;          
            state["Heroes"] = DotaData.AllHeroes;          
            state["Abilities"] = DotaData.AllAbilities;           
            state["Items"] = DotaData.DefaultItems;
            state["Events"] = DotaData.Events;

            //Bind the DataClass enum
            state.DoString("DataClass = {}");
            state["DataClass.Default"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Default;
            state["DataClass.Override"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Override;
            state["DataClass.Custom"] = DotaDataObject.DataObjectInfo.ObjectDataClass.Custom;


        }
Beispiel #2
0
        public Item(XmlNode node, Lua lua)
            : this()
        {
            Name = node.SelectSingleNode("name").InnerText;
            Description = node.SelectSingleNode("desc").InnerText;

            XmlNode field = node.SelectSingleNode("field");

            if (field != null)
            {
                FieldUsage = new FieldUsageRecord();

                FieldUsage.Target = (FieldTarget)Enum.Parse(typeof(FieldTarget), field.SelectSingleNode("@target").Value);

                char targetParameterName = Char.ToLower(FieldUsage.Target.ToString()[0]);

                string canUse = String.Format("return function ({0}) {1} end", targetParameterName, field.SelectSingleNode("canUse").InnerText);
                string use = String.Format("return function ({0}) {1} end", targetParameterName, field.SelectSingleNode("use").InnerText);

                try
                {
                    FieldUsage.CanUse = (LuaFunction)lua.DoString(canUse).First();
                    FieldUsage.Use = (LuaFunction)lua.DoString(use).First();
                }
                catch (Exception e)
                {
                    throw new ImplementationException("Error in item field scripts; id = " + ID, e);
                }
            }

            XmlNode battle = node.SelectSingleNode("battle");

            if (battle != null)
            {
                BattleUsage = new BattleUsageRecord();

                BattleUsage.Target = (BattleTarget)Enum.Parse(typeof(BattleTarget), battle.SelectSingleNode("@target").Value);

                XmlNode intendedForEnemiesNode = battle.SelectSingleNode("@intendedForEnemies");

                if (intendedForEnemiesNode != null)
                {
                    BattleUsage.IntendedForEnemies = Boolean.Parse(intendedForEnemiesNode.Value);
                }

                string use = String.Format("return function (s, t) {0} end", battle.SelectSingleNode("use").InnerText);

                try
                {
                    BattleUsage.Use = (LuaFunction)lua.DoString(use).First();
                }
                catch (Exception e)
                {
                    throw new ImplementationException("Error in item battle scripts; id = " + ID, e);
                }
            }
        }
Beispiel #3
0
		static void Main (string [] args)
		{
			using (var l = new Lua ()) {
				l.LoadCLRPackage ();
				l.DoString (" import ('ConsoleTest') ");
				l.DoString (@"
						Program.Method (1)
				");
			}
		}
Beispiel #4
0
		static void Main (string [] args)
		{
			using (var l = new Lua ()) {
				l.LoadCLRPackage ();
				l.DoString (" import ('ConsoleTest', 'NLuaTest.Mock') ");
				l.DoString (@"
						e1 = Entity()
						e2 = Entity ('Another world')
						e3 = Entity (10)
				");
			}
		}
Beispiel #5
0
		public void TestCLRPackage ()
		{
			using (Lua lua = new Lua ()) {
				lua.LoadCLRPackage ();

				lua.DoString ("import ('NLuaTest', 'NLuaTest.Mock') ");
				lua.DoString ("test = TestClass()");
				lua.DoString ("test:setVal(3)");
				object[] res = lua.DoString ("return test");
				TestClass test = (TestClass)res [0];
				Assert.AreEqual (3, test.testval);
			}
		}
Beispiel #6
0
	void Start () {
        lua = new Lua();
        // 加载定义脚本
        lua.DoString(CommonLuaScript.text);
        lua.DoString(BindLuaScript.text);

        lua["gameObject"] = gameObject;
        lua["transform"] = transform;

        LuaFunction luaFunc = lua.GetFunction("test");
        luaFunc.Call();

	}
Beispiel #7
0
		public void TestUseNSUrl ()
		{
			using (Lua lua = new Lua ()) {
				lua.LoadCLRPackage ();

				lua.DoString ("import ('monotouch', 'MonoTouch.Foundation') ");
				lua.DoString ("testURL = NSUrl('http://nlua.org/?query=param')");
				lua.DoString ("host = testURL.Host");

				object res = lua["host"];
				string host = (string)res;
				Assert.AreEqual ("nlua.org", host);
			}
		}
 private void Button_Run_Click(object sender, RoutedEventArgs e)
 {
     Lua lua = new Lua();
     lua["Robot"] = _luaProxyRobot;
     try
     {
         lua.DoString(@"import = function () end");
         lua.DoString(TextBox_Script.Text);
     }
     catch (Exception ex)
     {
         AppendToLog("Exception: \n" + ex.ToString());
     }
 }
Beispiel #9
0
		public void TestNullable ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("luanet.load_assembly('mscorlib')");
				lua.DoString ("luanet.load_assembly('NLuaTest')");
				lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
				lua.DoString ("test=TestClass()");
				lua.DoString ("val=test.NullableBool");
				Assert.AreEqual (null, (object)lua ["val"]);
				lua.DoString ("test.NullableBool = true");
				lua.DoString ("val=test.NullableBool");
				Assert.AreEqual (true, (bool)lua ["val"]);
			}
		}
Beispiel #10
0
		public void LuaDelegateValueTypesReturnReferenceType ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("luanet.load_assembly('NLuaTest')");
				lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
				lua.DoString ("test=TestClass()");
				lua.DoString ("function func(x,y) return TestClass(x+y); end");
				lua.DoString ("test=TestClass()");
				lua.DoString ("a=test:callDelegate4(func)");
				int a = (int)lua.GetNumber ("a");
				Assert.AreEqual (5, a);
				//Console.WriteLine("delegate returned: "+a);
			}
		}
Beispiel #11
0
 /// <summary>
 /// Try to execute a Lua command given in a string
 /// </summary>
 /// <param name="luaCommand"></param>
 public static bool executeCommand(string luaCommand)
 {
     Lua lua = new Lua();
     lua.LoadCLRPackage();
     lua.DoString(@" import ('TextRPG', 'TextRPG')
        import ('System') ");
     try {
         lua.DoString(luaCommand);
         return true;
     }
     catch (Exception e)
     {
         return false;
     }
 }
Beispiel #12
0
		public void ThrowException ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("luanet.load_assembly('mscorlib')");
				lua.DoString ("luanet.load_assembly('NLuaTest')");
				lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
				lua.DoString ("test=TestClass()");
				lua.DoString ("err,errMsg=pcall(test.exceptionMethod,test)");
				bool err = (bool)lua ["err"];
				Exception errMsg = (Exception)lua ["errMsg"];
				Assert.False (err);
				Assert.NotNull (errMsg.InnerException);
				Assert.AreEqual ("exception test", errMsg.InnerException.Message);
			}
		}
Beispiel #13
0
 /// <summary>
 /// Runs Lua code and returns an array of return values.
 /// </summary>
 /// <returns>
 /// An array of return values, or <c>null</c> if the code generates an error.
 /// </returns>
 /// <param name='luaCode'>
 /// The Lua code to run. If you want a return value, this string should usually start with
 /// "<c>return</c>".
 /// </param>
 /// <param name='debug'>
 /// If <c>true</c>, logs the Lua command to the console.
 /// </param>
 /// <param name='allowExceptions'>
 /// If <c>true</c>, exceptions are passed up to the caller. Otherwise they're caught and logged but ignored.
 /// </param>
 public static object[] RunRaw(string luaCode, bool debug, bool allowExceptions)
 {
     try
     {
         if (string.IsNullOrEmpty(luaCode))
         {
             return(null);
         }
         else
         {
             if (Debug.isDebugBuild && debug)
             {
                 Debug.Log(string.Format("{0}: Lua({1})", new System.Object[] { DialogueDebug.Prefix, luaCode }));
             }
             WasInvoked = true;
             return(luaVM.DoString(luaCode));
         }
     }
     catch (Exception e)
     {
         if (Debug.isDebugBuild && !MuteExceptions)
         {
             Debug.LogError(string.Format("{0}: Lua code '{1}' threw exception '{2}'", new System.Object[] { DialogueDebug.Prefix, luaCode, e.Message }));
         }
         if (allowExceptions)
         {
             throw e;
         }
         else
         {
             return(null);
         }
     }
 }
Beispiel #14
0
 internal static string Execute(string content, CmdContext msg)
 {
     using (NLua.Lua lua = new NLua.Lua())
         using (PrintProxy proxy = new PrintProxy())
         {
             lua.RegisterFunction("print", proxy, proxy.GetType().GetMethod("Print", new Type[] { typeof(object[]) }));
             string code;
             using (StreamReader sr = new StreamReader(typeof(Lua).Assembly.GetManifestResourceStream("DuckBot.Resources.Sandbox.lua")))
                 code = sr.ReadToEnd();
             try
             {
                 const string template = "args = {...};rawText,sender,server,channel=args[1],args[2],args[3],args[4]\n";
                 string       source   = template + content;
                 using (LuaFunction func = (LuaFunction)lua.DoString(code, "sandbox")[0])
                 {
                     object[] rets = func.Call(source, msg.Args, msg.Sender, msg.Server, msg.Channel);
                     if (rets.Length >= 2)
                     {
                         object[] arr = new object[rets.Length - 1];
                         Array.Copy(rets, 1, arr, 0, arr.Length);
                         proxy.Print(arr);
                     }
                     string res = proxy.ToString().Trim();
                     return(res.Length == 0 ? msg.GetString("Strings.ret_empty_script") : res);
                 }
             }
             catch (NLua.Exceptions.LuaScriptException ex) { return(msg.GetString("err_generic") + ": " + ex.Message + "\n``` " + ex.Source + " ```"); }
         }
 }
        public bool Awakening()
        {
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon         += GameOnOnLevelWon;
            env = new NLua.Lua();
            env.LoadCLRPackage();
            env["this"]       = this; // Give the script access to the gameobject.
            env["transform"]  = transform;
            env["gameObject"] = gameObject;
            env["enabled"]    = enabled;
            env["useAPI"]     = new Action(UseAPI);
            env["disableAPI"] = new Action(DisableAPI);

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                env["besiege"] = Besiege._besiege;
            }
            try
            {
                env.DoString(source);
            }
            catch (NLua.Exceptions.LuaException e)
            {
                Debug.LogError(FormatException(e), context: gameObject);
                return(false);
            }
            Call("Awake");
            return(true);
        }
Beispiel #16
0
        private static void Main()
        {
            Console.Title = "NLua Test Environment";

            object x = 3;
            double y = (double)(int)x;

            string script = "function add(a, b) return a + b, a, b; end\n" +
                            "local function sub(a, b) return a - b; end\n" +
                            "local function mul(a, b) return a * b; end\n" +
                            "local function div(a, b) return a / b; end\n" +
                            "print(\"Adding 1 and 5 gives us \" .. add(1, 5));\n" +
                            "print(\"Subtracting 8 and 2 gives us \" .. sub(8, 2));\n" +
                            "print(\"Multiplying 32 and 1024 gives us \" .. mul(32, 1024));\n" +
                            "print(\"Dividing 8 and 2 gives us \" .. div(8, 2));\n";

            using (dynamic lua = new Lua())
            {
                lua.LoadStandardLibrary(LuaStandardLibraries.Basic);
                lua.DoString("print(\"This confirms the Lua environment has loaded the basic standard library.\\nThe Lua environment is operational.\");");
                lua.DoFile("TestScript.lua");

                lua.v = "test";

                object[] table = lua.x;
            }

            Console.ReadLine();
        }
Beispiel #17
0
        public void Init()
        {
            if (IsInitialized)
                throw new InvalidOperationException("Already Initialized!");

            if (_state != null) _state.Dispose();
            
            _state = new Lua();
            _state.LoadCLRPackage();

            _state.DoString(@"luanet.load_assembly('WGestures.Core');
                              luanet.load_assembly('WindowsInput');
                              luanet.load_assembly('WGestures.Common');

                              GestureModifier=luanet.import_type('WGestures.Core.GestureModifier');  
                              VK=luanet.import_type('WindowsInput.Native.VirtualKeyCode');
                              Native=luanet.import_type('WGestures.Common.OsSpecific.Windows.Native');
                            ", "_init");

            _state["Input"] = Sim.Simulator;
            _state.RegisterFunction("ReportStatus", this, typeof(ScriptCommand).GetMethod("OnReportStatus"));

            if(InitScript != null)
            {
                DoString(InitScript, "Init");
            }
            
            IsInitialized = true;
        }
        public bool Awakening()
        {
            spaar.ModLoader.Game.OnSimulationToggle += GameOnOnSimulationToggle;
            spaar.ModLoader.Game.OnLevelWon += GameOnOnLevelWon;
            env = new NLua.Lua();
            env.LoadCLRPackage();
            env["this"] = this; // Give the script access to the gameobject.
            env["transform"] = transform;
            env["gameObject"] = gameObject;
            env["enabled"] = enabled;
            env["useAPI"] = new Action(UseAPI);
            env["disableAPI"] = new Action(DisableAPI);

            if (Settings.useAPI)
            {
                Besiege.SetUp();
                env["besiege"] = Besiege._besiege;
            }
            try
            {
                env.DoString(source);
            }
            catch (NLua.Exceptions.LuaException e)
            {
                Debug.LogError(FormatException(e), context: gameObject);
                return false;
            }
            Call("Awake");
            return true;
        }
Beispiel #19
0
        static void Main(string [] args)
        {
            using (Lua lua = new Lua ()) {
                lua.LoadCLRPackage ();

                lua.DoString (@" import ('ConsoleTest')
                              v = Vector()
                              v.x = 10
                              v.y = 3
                              v = v*2 ");

                var v = (ConsoleTest.Vector)lua ["v"];

                lua.DoString (@" x = 2*v");
                var x = (Vector)lua ["x"];
            }
        }
Beispiel #20
0
 static void Main(string [] args)
 {
     using (var l = new Lua ()) {
         Action c = () => { Console.WriteLine ("Ola"); };
         l ["d"] = c;
         l.DoString (" d () ");
     }
 }
Beispiel #21
0
        public Event(Events e)
        {
            IsExclusive = false;
            ElapsedTime = 0;

            lua = new Lua();
            lua["event"] = this;
            if (GameObject.Find("Player") != null)
                lua["player"] = GameObject.Find("Player").GetComponent<PlayerController>();
            if (GameObject.Find("Manager").GetComponent<StageScript>() != null)
                lua["stage"] = GameObject.Find("Manager").GetComponent<StageScript>();

            lua.DoString(Resources.Load<TextAsset>(SOURCE_FILE_FOLDER + "Utilities.lua").text);
            lua.DoString(GetLuaSource(e));

            coroutine = new LuaCoroutine(lua);
        }
Beispiel #22
0
 private void Form1_Load(object sender, EventArgs e)
 {
     /*Lua a = new Lua();
     a.DoFile("1.lua");
     var c = a["myvar"];
     Trace.WriteLine(c);*/
     Lua state = new Lua();
     double val = 12.0;
     state["x"] = val;
     var res = state.DoString("return 10 + x*(5 + 2)")[0];
     state.DoString("y = 10 + x*(5 + 2)");
     var y = state["y"];
     Trace.WriteLine(y);
     state.DoString(@"function ScriptFunc() end");
     var scriptFunc = state["ScriptFunc"] as LuaFunction;
     var ress = scriptFunc.Call()[0];
     Trace.WriteLine(ress);
 }
Beispiel #23
0
		public void ThrowUncaughtException ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("luanet.load_assembly('mscorlib')");
				lua.DoString ("luanet.load_assembly('NLuaTest')");
				lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
				lua.DoString ("test=TestClass()");

				try {
					lua.DoString ("test:exceptionMethod()");
					//failed
					Assert.True (false);
				} catch (Exception) {
					//passed
					Assert.True (true);
				}
			}
		}
Beispiel #24
0
 public BubbleLua(Lua lua, bool init = true)
 {
     Lua = lua;
     if (!init)
         return;
     Lua.NewTable ("bubble");
     Bubble = (LuaTable)Lua ["bubble"];
     lua.DoString (EmbeddedResources.GetString ("BubbleEngine.LuaAPI.bubbleinternal.lua"));
 }
Beispiel #25
0
        public void TestBasicFunctionality()
        {
            Lua lua = new Lua();

            ////
            //TestLuaFunctions testLuaFunctions = new TestLuaFunctions();
            //lua.RegisterFunction("Say", testLuaFunctions, testLuaFunctions.GetType().GetMethod("Say"));
            //lua.RegisterFunction("CreateInstance", typeof(TestLuaFunctions).GetMethod("CreateInstance"));
            //lua.DoString("Say('pouet')");
            //lua.DoString("instance = CreateInstance()");
            //lua.DoString("instance:Say('woohoo')");

            //TestLuaFunctions externalInstance = (TestLuaFunctions) lua["instance"];
            //externalInstance.Say("using externally created instance to call Say");

            //
            CreateWorld();

            ITestCharacter testCharacter = TestCharacter.Create();

            lua["testcharacter"] = testCharacter;

            lua.RegisterFunction("print", typeof(LuaOutput).GetMethod("Print"));
            //lua["this"] = bigBadMob;
            //lua["room"] = DependencyContainer.Instance.GetInstance<IWorld>().Rooms.First();
            lua.RegisterFunction("getCharacter", this, GetType().GetMethod("GetCharacter"));
            lua.DoString(
                @"print('this is a debug message')
            local this = getCharacter()
            cName = this.DisplayName
            function luanet.each(o)
               local e = o:GetEnumerator()
               return function()
                  if e:MoveNext() then
                    return e.Current
                 end
               end
            end

            local each = luanet.each;
            for c in each(this.Room.People) do
                local name = c == getCharacter() and 'me' or c.DisplayName;
                print('in room:'..name);
            end

           -- local globals = _G
            --for g in each(globals) do
            --    print('global:'..tostring(g));
            --end");
            //doesn't work    lua.DoString("function this.pouet(s) print(s) end");
            var cName          = lua["cName"];
            var luanet         = lua["luanet"];
            var globals        = lua["_G"];
            var testCharacter2 = lua["testcharacter"];

            lua.Close();
        }
Beispiel #26
0
        static void Main(string [] args)
        {
            using (Lua lua = new Lua ()) {
                lua.DoString ("luanet.load_assembly('mscorlib')");
                lua.DoString ("luanet.load_assembly('ConsoleTest')");
                lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
                lua.DoString ("test=TestClass()");

                try {
                    lua.DoString ("test:exceptionMethod()");
                    //failed
                    //Assert.True (false);
                } catch (Exception) {
                    //passed
                    //Assert.True (true);
                }
            }
        }
Beispiel #27
0
		public void Setup()
		{
			lua = new Lua ();
			lua.RegisterFunction ("WriteLineString", typeof (Console).GetMethod ("WriteLine", new Type [] { typeof (String) }));
			
			lua.DoString (@"
			function print (param)
				WriteLineString (tostring(param))
			end
			");
		}
Beispiel #28
0
 public static void DoString(string script)
 {
     try
     {
         L.DoString(script);
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message);
     }
 }
        /// <summary>
        /// Registers a command to the Lua kernel.
        /// </summary>
        /// <param name="functionName">Lua registered function name to run. Looks like "_{guildId}_{cmdName}".</param>
        /// <param name="code">Function code. Does not include the header or ending, just the body.</param>
        /// <returns></returns>
        public async Task RegisterCommand(string functionName, string code)
        {
            using var c = new CancellationTokenSource();
            c.CancelAfter(CustomCommandExecTimeout);

            await Task.Run(() =>
            {
                _luaState.DoString($"function {functionName} (args) {code} end");
                _commands[functionName] = _luaState.GetFunction(functionName);
            }, c.Token);
        }
Beispiel #30
0
        public ScriptTrigger(Lua luaState, IZone zone, Script tringgerScript, IEnumerable <Entity> entities)
        {
            Zone = zone;
            luaState.DoString(tringgerScript.Text);
            _onInActionLua  = luaState["OnInAction"]  as LuaFunction;
            _onOutActionLua = luaState["OnOutAction"] as LuaFunction;
            _entities       = entities;
            _inside         = _entities.ToDictionary(x => x, zone.IsInside);

            ScriptingAPI.I.Core.Log.Info($"[Script] Loaded trigger script \"{tringgerScript.Path}.lua\".");
        }
Beispiel #31
0
		void Start()
		{
			LuaState = new Lua();
			LuaState.LoadCLRPackage();
			LuaState.LoadUnityExpand();

			var ret = LuaState.DoString(@"return require 'requiretest'");
			TestLib = ret[0] as LuaTable;

			var startCallback = TestLib["Start"] as LuaFunction;
			startCallback.Call(this.gameObject);
		}
Beispiel #32
0
        public static Lua GetLua()
        {
            Lua lua = new Lua();
            lua.LoadCLRPackage();

            lua.DoString(@" import ('Systen') ");
            lua.DoString(@" import ('Systen.IO') ");
            lua.DoString(@" import ('Systen.Text') ");
            lua.DoString(@" import ('Systen.Text.RegularExpressions') ");

            lua.DoString(" import ('" + typeof(Seven).Assembly.GetName().Name + "') ");
            lua.DoString(Resource.GetTextFromResource("lua.scripts", typeof(Seven).Assembly));
            lua.DoString("Element = luanet.import_type(\"Atmosphere.Reverence.Seven.Asset.Element\")");
            lua.DoString("Status = luanet.import_type(\"Atmosphere.Reverence.Seven.Asset.Status\")");
            lua.DoString("Party = luanet.import_type(\"Atmosphere.Reverence.Seven.Party\")");

            return lua;
        }
        public CustomCommandProvider(AldertoDbContext context)
        {
            _context  = context;
            _luaState = new NLua.Lua();
            _commands = new Dictionary <string, LuaFunction>();

            // Load Lua code
            // TODO: Load lua code. Uncomment below
            //_luaState.LoadCLRPackage();
            //_luaState.DoString("import ('Alderto.Bot', 'Alderto.Bot.Commands')");

            // Prevent additional namespaces to be added
            _luaState.DoString("import = function () end");
        }
Beispiel #34
0
 private bool Run()
 {
     try
     {
         Debug.Log("DoString:\n" + script);
         lua.DoString(script);
         Debug.Log("OK");
         return(true);
     }
     catch (Exception ex)
     {
         Debug.LogException(ex);
         return(false);
     }
 }
Beispiel #35
0
 public static void runLua(String code)
 {
     try
     {
         Lua vm = new Lua();
         vm.InstallRunGNatives();
         if (Static.isCLR) vm.LoadCLRPackage();
         vm.DoString(code);
     }
     catch (Exception e)
     {
         log.error("Erro: " + RunGEngine.decipherCatch(e));
         Static.fine = false;
     }
 }
Beispiel #36
0
	void Awake() {
		env = new Lua();
		env.LoadCLRPackage();

		env["this"] = this; // Give the script access to the gameobject.
		env["transform"] = transform;
		
		//System.Object[] result = new System.Object[0];
		try {
			//result = env.DoString(source);
			env.DoString(source);
		} catch(NLua.Exceptions.LuaException e) {
			Debug.LogError(FormatException(e), gameObject);
		}

	}
Beispiel #37
0
 public void DoFile(Lua vm)
 {
     try
     {
         vm.DoString(Lua, System.IO.Path.GetFileName(Path.LocalPath));
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         if (e.InnerException != null)
         {
             Console.WriteLine(e.InnerException.Message);
             Console.WriteLine(e.InnerException.StackTrace);
         }
     }
 }
Beispiel #38
0
    /*
    const string source = @"luanet.load_assembly('mscorlib')
                            luanet.load_assembly('test')
                            Class1 = luanet.import_type('test.Class1')
                            cc = Class1()
                            cc:Log('fffffffffffffffffffffffff')
                            print('gggggggggggggggggggg---luaaaaaaaaaaaaaaaa')
                        ";

    Debug.WriteLine("start app========================>>>>>>>>>>>");
    using (Lua lua = new Lua()) {
        lua.LoadCLRPackage();
        Type[] types = new Type[] { typeof(String) };
        lua.RegisterFunction("print", null, typeof(Debug).GetMethod("WriteLine", types));
        lua.DoString(source);
    }
     * */

    // Use this for initialization
	IEnumerator Start () {
        yield return new WaitForSeconds(3);
        env = new Lua();
        env.LoadCLRPackage();

        env["this"] = this; // Give the script access to the gameobject.
        env["transform"] = transform;

        //System.Object[] result = new System.Object[0];
        try {
            //result = env.DoString(source);
            env.DoString(source);
        } catch (NLua.Exceptions.LuaException e) {
            Debug.LogError(FormatException(e), gameObject);
        }
        Call("Start");
	}
Beispiel #39
0
        static void Main(string [] args)
        {
            using (Lua lua = new Lua())
             		{
             lua.DebugHook += DebugHook;
             lua.SetDebugHook (NLua.Event.EventMasks.LUA_MASKLINE, 0);
             var a = new System.Numerics.Complex (10, 0);
             var b = new System.Numerics.Complex (0, 3);
             var x = a + b;

            // lua.LoadCLRPackage ();
             lua ["a"] = a;
             lua ["b"] = 1;
             var res = lua.DoString (@"return a + b")[0];

             		}
        }
Beispiel #40
0
        /// <summary>
        /// A label for displaying values obtained through Lua scripts.
        /// </summary>
        /// <param name="filePath">The path to the Lua script. The script must contain a GetValue() function, which returns the desired text to be displayed.</param>
        /// <param name="lua">Obtained by calling GetLua() on a WatchManager32Bit.</param>
        public LuaWatch(string filePath, Lua.Lua lua)
        {
            NLua.Lua n = new NLua.Lua();
            n.LoadCLRPackage();
            n.DoString("import ('DeSmuME_Watch', 'DeSmuME_Watch.Lua')");

            n.DoFile(filePath);
            luaGetValue = n.GetFunction("GetValue");
            this.lua    = lua;
            n["WATCH"]  = lua;

            if (luaGetValue == null)
            {
                throw new Exception("Lua script could not be loaded. Make sure it contains the function GetValue().");
            }

            this.AutoSize = true;
            this.SetText("?");
        }
        public static object ValueToLua(NLua.Lua lua, object value)
        {
            if (value is bool)
            {
                return(value);
            }
            if (value is Color c)
            {
                // var table = lua.NewTable();

                var r = c.R;
                var g = c.G;
                var b = c.B;
                var a = c.A;

                // todo: I don't really know the best way to do this
                return(lua.DoString($"return [{r}, {g}, {b}, {a}]")[0]);
            }

            throw new Exception(nameof(Value));
        }
Beispiel #42
0
        public void TestIntegration()
        {
            CreateWorld();

            Lua lua = new Lua();

            lua.RegisterFunction("print", typeof(LuaOutput).GetMethod("Print"));

            //// Create Lua table for each blueprint script table name
            //foreach (CharacterBlueprint blueprint in DependencyContainer.Instance.GetInstance<IWorld>().CharacterBlueprints.Where(x => x.ScriptTableName != null))
            //{
            //    if (lua.GetTable(blueprint.ScriptTableName) == null)
            //        lua.NewTable(blueprint.ScriptTableName);
            //}

            // Read scripts from file/immediate string
            lua.DoString(
                @"
mob1 = {}
function mob1:OnTick()
    print('OnTick:'..self.DisplayName..'  '..tostring(self));
    --for n in pairs(_G) do print(n) end
    --for n in pairs(self) do print(n) end
end
function mob1:OnSay(actor, msg)
    print('OnSay:['..self.DisplayName..'] heard ['..actor.DisplayName..'] saying ['..msg..']');
end

mob2 = {}
function mob2:OnTick()
    print('OnTick:'..self.DebugName);
end
function mob2:OnGreet(actor, from)
    print('OnGreet: ['..self.DebugName..'] saw ['..actor.DebugName..'] entering room from ['..tostring(from)..']');
    actor:GainExperience(10000000); -- <-- this should be forbidden, only a few information such as DisplayName, Room, ... should be available
end");

            // TODO: replace 'scripts' with parameter in ICharacter and initialize this in AddCharacter or in Character ctor
            List <CharacterScript> scripts = new List <CharacterScript>();

            foreach (ICharacter character in DependencyContainer.Instance.GetInstance <IWorld>().Characters.Where(x => x.Blueprint.ScriptTableName != null))
            {
                string scriptName = character.Blueprint.ScriptTableName;
                var    mobScript  = lua[scriptName];
                if (mobScript != null)
                {
                    CharacterScript script = new CharacterScript(lua, character, scriptName);
                    scripts.Add(script);
                }
            }

            // Call script from appropriate functions in Server
            foreach (ICharacter character in DependencyContainer.Instance.GetInstance <IWorld>().Characters)
            {
                CharacterScript script = scripts.FirstOrDefault(x => x.Character == character);
                script?.OnTick();
                script?.OnSay(DependencyContainer.Instance.GetInstance <IWorld>().Characters.Skip(1).First(), "woot");
            }

            CharacterScript mob1 = scripts.FirstOrDefault(x => x.Character == DependencyContainer.Instance.GetInstance <IWorld>().Characters.First());
            //mob1?.Pouet("tsekwa");

            CharacterScript mob2 = scripts.FirstOrDefault(x => x.Character == DependencyContainer.Instance.GetInstance <IWorld>().Characters.Skip(1).First());

            mob2?.OnGreet(DependencyContainer.Instance.GetInstance <IWorld>().Characters.First(), ExitDirections.SouthWest);

            var mob1InLua = lua["mob1"];

            lua.Close();
        }
Beispiel #43
0
 public object[] ExecScriptCode(string script_code)
 {
     return(m_LuaState.DoString(script_code));
 }
Beispiel #44
0
        /// <summary>
        /// Lua 脚本线程入口
        /// </summary>
        private void LuaScriptStart()
        {
            using (var luaObject = new NLua.Lua()) // Lua 对象
            {
                luaObject["C"] = this;             // // 提供给 Lua 可使用的接口
                luaObject.RegisterFunction("MessageBoxShow", typeof(MessageBox).GetMethod("Show", new Type[] { typeof(string) }));
                luaObject.RegisterFunction("CreateDataJudge", this, this.GetType().GetMethod("CreateDataJudge", new Type[] { typeof(string), typeof(string) }));
                luaObject.RegisterFunction("CreateDataClick", this, this.GetType().GetMethod("CreateDataClick", new Type[] { typeof(string), typeof(string) }));
                luaObject.RegisterFunction("Delay", this, this.GetType().GetMethod("Delay", new Type[] { typeof(int) }));
                luaObject.RegisterFunction("StopThread", this, this.GetType().GetMethod("StopThread"));
                //luaObject.RegisterFunction("Set_ChangeStatus",this,this.GetType().GetMethod("Set_ChangeStatus",new Type[] { typeof(string), typeof(Color), typeof(Color), typeof(bool)}));
                //luaObject.RegisterFunction("Set_AddMassage", this, this.GetType().GetMethod("Set_AddMassage", new Type[] { typeof(string) }));

                while (true)
                {
                    Set_AddMessage($"Lua脚本:{this._scriptName} 开始执行...");
                    if (Cycles == 0)
                    {
                    }
                    else if (ExecutedNumber >= Cycles)
                    {
                        break;
                    }
                    ExecutedNumber++;

                    WaitQueue();// 加入到消息队列
WorkStart:
                    try
                    {
                        // 改变状态栏
                        Set_ChangeStatus($"{ExecutedNumber}:Lua 脚本正在执行...", Color.White, Color.Orange);
                        // 执行读入的脚本
                        _luaScriptText.BaseStream.Position = 0;
                        var ret = luaObject.DoString(_luaScriptText.ReadToEnd()).First();

                        // 结束脚本工作
                        this.IsWorking = false;

                        // 是否循环
                        if (Cycles == 0)
                        {
                        }
                        else if (ExecutedNumber >= Cycles)
                        {
                            break;
                        }
                        Set_AddMessage($"{this._scriptName} 已挂起等待,等待时间:{WaitTime}");
                        Delay(2000);
                        var wt = new TimeSpan();
                        while (WaitTime > 0)
                        {
                            wt = Functions.MillisecondToTime(WaitTime);
                            Set_ChangeStatus($"{ExecutedNumber}:等待时间:{wt.Days * 24 + wt.Hours}:{wt.Minutes}:{wt.Seconds}", Color.White, Color.Lime);
                            Delay(1000);
                            WaitTime -= 1000;
                        }
                    }
                    catch (ThreadAbortException) { }
                    catch (NLua.Exceptions.LuaScriptException e)// 来自脚本的错误
                    {
                        if ((e.InnerException ?? e).GetType() == typeof(Exceptions.TimeOutException))
                        {
                            // 超时
                            OvertimeProcess();
                            goto WorkStart;
                        }
                        throw e;
                    }
                }
            }
        }
 public static LuaTable GetEmptyTable(this NLua.Lua state) => (LuaTable)state.DoString("return {}")[0];
        public Task <Module[]> GetInstalledAircraftModulesAsync()
        {
            Tracer.Info("Searching DCS for installed modules.");
#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
            return(Task.Run(async() =>
#pragma warning restore CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
            {
                var settingsService = _container.Resolve <ISettingsService>();
                var modules = new List <Module>();
                var install = settingsService.SelectedInstall;
                var autoupdateModules = new List <string>(install.Modules);

                autoupdateModules.Add("Su-25T");
                autoupdateModules.Add("TF-51D");

                if (!install.IsValidInstall)
                {
                    return modules.ToArray();
                }

                var aircraftFolders = Directory.GetDirectories(Path.Combine(install.Directory, "Mods//aircraft"));

                foreach (var folder in aircraftFolders)
                {
                    using (var lua = new NLua.Lua())
                    {
                        lua.State.Encoding = Encoding.UTF8;

                        var entryPath = Path.Combine(folder, "entry.lua");

                        lua.DoString(
                            @"function _(s) return s end
                                function _(s) return s end
                                function mount_vfs_liveries_path() end
                                function mount_vfs_texture_path() end
                                function mount_vfs_sound_path() end
                                function mount_vfs_model_path() end
                                function make_view_settings() end
                                function set_manual_path() end
                                function dofile() end
                                function plugin_done() end
                                function make_flyable() end
                                AV8BFM = {}
                                F86FM = {}
                                F5E = {}
                                FA18C = {}
                                F15FM = {}
                                FM = {}
                                M2KFM = {}
                                Mig15FM = {}
                                MIG19PFM = {}
                                SA342FM = {}
                                " + $"__DCS_VERSION__ = \"{install.Version}\"");

                        var directoryName = Path.GetDirectoryName(folder);

                        lua.DoString($"current_mod_path = \"{folder.Replace("\\", "\\\\")}\"");

                        var moduleId = string.Empty;
                        var skinsPath = string.Empty;
                        var displayName = string.Empty;

                        lua["declare_plugin"] = new Action <string, LuaTable>((id, description) =>
                        {
                            if (description.Keys.OfType <string>().All(k => k != "installed" && k != "update_id"))
                            {
                                return;
                            }

                            if (description.Keys.OfType <string>().All(k => k != "update_id"))
                            {
                                moduleId = description["fileMenuName"]?.ToString();
                            }
                            else
                            {
                                moduleId = description["update_id"]?.ToString();
                            }

                            skinsPath = ((LuaTable)((LuaTable)description["Skins"])[1])["dir"].ToString();
                            displayName = ((LuaTable)((LuaTable)description["Missions"])[1])["name"].ToString();
                        });

                        lua["make_flyable"] = new Action <string, string, LuaTable, string>((a, b, c, d) =>
                        {
                            if (displayName.Contains("_hornet"))
                            {
                                displayName = displayName.Split('_')[0];
                            }

                            if (!string.IsNullOrEmpty(moduleId) && autoupdateModules.Contains(moduleId) && moduleId != "FC3")
                            {
                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                    ViewportPrefix = moduleId.ToString().Replace(" ", "_").Replace("-", "_")
                                };
                                modules.Add(module);
                                Tracer.Info($"Found module {displayName}.");
                            }
                        });

                        try
                        {
                            lua.DoFile(entryPath);
                        }
                        catch (Exception e)
                        {
                            Tracer.Error(e);
                        }
                    }
                }

                return modules.ToArray();
            }));
        }
        public Task <Module[]> GetInstalledAircraftModulesAsync()
        {
            Tracer.Info("Searching DCS for installed modules.");

            var settingsService = _container.Resolve <ISettingsService>();
            var install         = settingsService.SelectedInstall;

            if (!install.IsValidInstall)
            {
                Tracer.Info("Current install is invalid, aborting...");
                return(Task.FromResult(_modules.Values.ToArray()));
            }

            return(Task.Run(() =>
            {
                var autoUpdateModules = new List <string>(install.Modules)
                {
                    "Su-25T",
                    "TF-51D"
                };

                var aircraftFolders = Directory.GetDirectories(Path.Combine(install.Directory, "Mods//aircraft"));

                foreach (var folder in aircraftFolders)
                {
                    using (var lua = new NLua.Lua())
                    {
                        lua.State.Encoding = Encoding.UTF8;

                        var entryPath = Path.Combine(folder, "entry.lua");

                        lua.DoString(
                            @"function _(s) return s end
                                function _(s) return s end
                                function mount_vfs_liveries_path() end
                                function mount_vfs_texture_path() end
                                function mount_vfs_sound_path() end
                                function mount_vfs_model_path() end
                                function make_view_settings() end
                                function set_manual_path() end
                                function dofile() end
                                function plugin_done() end
                                function make_flyable() end
                                function MAC_flyable() end
                                function turn_on_waypoint_panel() end
                                AV8BFM = {}
                                F86FM = {}
                                F5E = {}
                                FA18C = {}
                                F15FM = {}
                                F16C = {}
                                FM = {}
                                M2KFM = {}
                                Mig15FM = {}
                                MIG19PFM = {}
                                SA342FM = {}
                                JF17_FM = {}
                                function add_plugin_systems() end
                                " + $"__DCS_VERSION__ = \"{install.Version}\"");

                        var directoryName = Path.GetDirectoryName(folder);

                        lua.DoString($"current_mod_path = \"{folder.Replace("\\", "\\\\")}\"");

                        var moduleId = string.Empty;
                        var skinsPath = string.Empty;
                        var displayName = string.Empty;

                        lua["declare_plugin"] = new Action <string, LuaTable>((id, description) =>
                        {
                            if (description.Keys.OfType <string>().All(k => k != "installed" && k != "update_id"))
                            {
                                return;
                            }

                            moduleId =
                                description.Keys.OfType <string>().All(k => k != "update_id")
                                    ? description["fileMenuName"]?.ToString()
                                    : description["update_id"]?.ToString();

                            var skinsTable = description["Skins"] as LuaTable;

                            if (skinsTable != null)
                            {
                                skinsPath = ((LuaTable)skinsTable[1])["dir"].ToString();
                            }

                            var missionsTable = description["Missions"] as LuaTable;

                            if (missionsTable != null)
                            {
                                displayName = ((LuaTable)missionsTable[1])["name"].ToString();
                            }
                        });

                        var makeFlyableAction = new Action <string, string, LuaTable, string>((a, b, c, d) =>
                        {
                            if (displayName.Contains("_hornet"))
                            {
                                displayName = displayName.Split('_')[0];
                            }

                            if (_modules.ContainsKey($"{moduleId}_{a}"))
                            {
                                return;
                            }

                            if (!string.IsNullOrEmpty(moduleId) && autoUpdateModules.Contains(moduleId) && moduleId != "FC3")
                            {
                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName}.");
                            }
                            else if (moduleId == "FC3")
                            {
                                //fc3Added = true;

                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    IsFC3 = true,
                                    FC3ModuleId = a,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName} {a}.");
                            }
                            else
                            {
                                Tracer.Debug($"Not loading module '{moduleId} - {displayName}' parameters ('{a}', '{b}', '{d}'.");
                            }
                        });

                        lua["make_flyable"] = makeFlyableAction;
                        lua["MAC_flyable"] = makeFlyableAction;

                        try
                        {
                            lua.DoFile(entryPath);
                        }
                        catch (Exception e)
                        {
                            Tracer.Error(e.Message);
                        }
                    }
                }

                return _modules.Values.ToArray();
            }));
        }
 protected object DoString(string lua)
 {
     return(_lua.DoString(lua));
 }
 public void Execute(string script)
 {
     _lua.DoString(script);
 }
        private static Lua CreateLuaContext(IList <Mod> modList)
        {
            var lua = new Lua();

            lua.State.Encoding = Encoding.UTF8;
            lua.DoString(File.ReadAllText("pprint.lua"), "<ppriunt>");
            lua.DoString(File.ReadAllText("serpent.lua"), "<serpent>");

            lua.DoString(@"
defines = {}

defines.difficulty_settings = {}
defines.difficulty_settings.recipe_difficulty = {
    normal = 'normal',
}
defines.difficulty_settings.technology_difficulty = {
    normal = 'normal',
}

defines.direction = {
    north = 'north',
    east = 'east',
    south = 'south',
    west = 'west',
}

defines.entity_status = {}
defines.entity_status.working = nil
defines.entity_status.no_power = nil
defines.entity_status.no_fuel = nil
defines.entity_status.no_recipe = nil
defines.entity_status.no_input_fluid = nil
defines.entity_status.no_research_in_progress = nil
defines.entity_status.no_minable_resources = nil
defines.entity_status.low_input_fluid = nil
defines.entity_status.low_power = nil
defines.entity_status.disabled_by_control_behavior = nil
defines.entity_status.disabled_by_script = nil
defines.entity_status.fluid_ingredient_shortage = nil
defines.entity_status.fluid_production_overload = nil
defines.entity_status.item_ingredient_shortage = nil
defines.entity_status.item_production_overload = nil
defines.entity_status.marked_for_deconstruction = nil
defines.entity_status.missing_required_fluid = nil
defines.entity_status.missing_science_packs = nil
defines.entity_status.waiting_for_source_items = nil
defines.entity_status.waiting_for_space_in_destination = nil
defines.entity_status.waiting_to_launch_rocket = nil
", "<defines>");

            lua.DoString(@"
data = {}
data.raw = {}
function merge(t1, t2)
    if t1 == nil then return t2 end
    for k, v in pairs(t2) do
        if (type(v) == 'table') and (type(t1[k] or false) == 'table') then
            merge(t1[k], t2[k])
        else
            t1[k] = v
        end
    end
    return t1
end
-- LINE 15
function data:extend(t)
    -- print('############')
    -- pprint(t)
    for k, v in pairs(t) do
        -- print('-----------------')
        -- pprint(k)
        -- pprint(v)
        if type(v) == 'table' and v.type ~= nil then
            if self.raw[v.type] == nil then
                self.raw[v.type] = {}
            end
            self.raw[v.type][v.name] = merge(self.raw[v.type][v.name], v)
        end
    end
end
function table_size(t)
    local count = 0
    for k, v in pairs(t) do
        count = count + 1
    end
    return count
end
", "<startup>");
            lua.NewTable("mods");
            var modTable = lua.GetTable("mods");

            foreach (var mod in modList)
            {
                modTable[mod.InternalName] = mod.Version.ToString(3);
            }

            string TranslateName(string name)
            {
                var path = (string)lua.DoString(@"function script_path()
                    local str = debug.getinfo(3, 'S')
                    return str.source
                end

                return script_path()")[0];

                if (path.EndsWith(".lua"))
                {
                    var lastIndex = path.LastIndexOfAny(new[] { '/', '\\' });
                    path = path.Remove(lastIndex);
                }
                else
                {
                    path = null;
                }

                name = name.Replace('.', '/');
                if (!name.EndsWith(".lua"))
                {
                    name += ".lua";
                }

                if (currentMod.FileExists(name))
                {
                    return("__" + currentMod.InternalName + "__/" + name);
                }

                var modName = name.Split('/')[0];

                if (Regex.IsMatch(modName, "^__.+__$"))
                {
                    modName = modName[2..^ 2];
                    var mod = modList.FirstOrDefault(mod => mod.InternalName == modName);
                    if (mod != null)
                    {
                        return(name);
                    }
                }