Beispiel #1
0
        public static void Main1(string[] args)
        {
            // create lua script engine
            using (var l = new Lua())
            {
                // create an environment, that is associated to the lua scripts
                dynamic g = l.CreateEnvironment <LuaGlobal>();

                // register new functions
                g.print = new Action <object[]>(Print);
                g.read  = new Func <string, string>(Read);


                var chunk = l.CompileChunk(ProgramSource, "test.lua", new LuaCompileOptions()
                {
                    DebugEngine = LuaStackTraceDebugger.Default
                });                                                                                                                             // compile the script with debug informations, that is needed for a complete stack trace
                var chunk2 = l.CompileChunk(ProgramSource2, "test2.lua", new LuaCompileOptions()
                {
                    DebugEngine = LuaStackTraceDebugger.Default
                });                                                                                                                                // compile the script with debug informations, that is needed for a complete stack trace

                try
                {
                    g.dochunk(chunk);  // execute the chunk
                    g.dochunk(chunk2); // execute the chunk
                }
                catch (Exception e)
                {
                    Console.WriteLine("Expception: {0}", e.Message);
                    var d = LuaExceptionData.GetData(e); // get stack trace
                    Console.WriteLine("StackTrace: {0}", d.FormatStackTrace(0, false));
                }
            }
        } // Main
Beispiel #2
0
        public void TestArithmetic15()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;

                dynamic g = l.CreateEnvironment();
                TestResult(g.dochunk("return a // b", "dummy", "a", 15, "b", 3), 5);
                TestResult(g.dochunk("return a // b", "dummy", "a", 5.2, "b", 2), (long)2);

                TestResult(g.dochunk("return a & b", "dummy", "a", 3.0, "b", 2), (long)2);
                TestResult(g.dochunk("return a | b", "dummy", "a", 2.0, "b", 3), (long)3);
                TestResult(g.dochunk("return a ~ b", "dummy", "a", 3.0, "b", 2), (long)1);
                TestResult(g.dochunk("return a << b", "dummy", "a", 1.0, "b", 8), (long)256);
                TestResult(g.dochunk("return a >> b", "dummy", "a", 256.0, "b", 8), (long)1);

                LuaChunk c1 = l.CompileChunk("return a ~ b", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(int)));
                TestResult(g.dochunk(c1, 3.2, 2), (long)1);
                TestResult(g.dochunk(c1, "3.2", 2), (long)1);
                TestResult(g.dochunk(c1, ShortEnum.Drei, 2), 1);
                TestResult(g.dochunk(c1, new Nullable <short>(3), 2), 1);
                LuaChunk c2 = l.CompileChunk("return a() ~ b", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(int)));
                TestResult(g.dochunk(c2, new Func <LuaResult>(() => new LuaResult(3.2)), 2), (long)1);
                TestResult(g.dochunk(c2, new Func <LuaResult>(() => new LuaResult(new TestOperator(3))), 2), new TestOperator(1));
                TestResult(g.dochunk(c2, new Func <LuaResult>(() => new LuaResult(new Nullable <float>(3.2f))), 2), 1);
            }
        }
 /// <summary>
 /// Add a script to the given environment
 /// </summary>
 /// <param name="environment">Name of script environment.</param>
 /// <param name="name">Name of script.</param>
 /// <param name="fileOrSource">File if next parameter is false (default), or literal source if true.</param>
 /// <param name="isSource">Preceeding argument is source code? Else, it's a filename.</param>
 /// <param name="par">Optional list of parameters for chunk. You are required to pass any parameters defined here
 /// when running the script.</param>
 public void AddScript(string environment, string name, string fileOrSource,
                       bool isSource = false, params KeyValuePair <string, Type>[] par)
 {
     try
     {
         // Compile script text or file to a LuaChunk, add to provided LuaPortableGlobal environment
         if (isSource)
         {
             var chunk = _context.CompileChunk(fileOrSource, name,
                                               new LuaCompileOptions()
             {
                 DebugEngine = LuaStackTraceDebugger.Default
             }, par);
             _environments[environment].AddScript(name, chunk);
         }
         else
         {
             var chunk = _context.CompileChunk(fileOrSource,
                                               new LuaCompileOptions()
             {
                 DebugEngine = LuaStackTraceDebugger.Default
             }, par);
             _environments[environment].AddScript(name, chunk);
         }
     }
     catch (Exception e)
     {
         DebugHelper.logError("AddScript()", e.Message);
         throw e;
     }
 }
Beispiel #4
0
        }         // proc Exception01

        private void ExceptionStackCore(LuaCompileOptions options)
        {
            using (var lua = new Lua())
            {
                var g     = lua.CreateEnvironment();
                var chunk = lua.CompileChunk(
                    Lines(
                        "do",
                        "  error('test');",
                        "end(function (e) return e; end);"
                        ),
                    "test.lua", options
                    );
                try
                {
                    if (chunk.Run(g)[0] is LuaRuntimeException ex)
                    {
                        var data = LuaExceptionData.GetData(ex, true);
                        Assert.AreEqual(2, data[3].LineNumber);
                    }
                    else
                    {
                        Assert.Fail();
                    }
                }
                catch (LuaRuntimeException)
                {
                    Assert.Fail();
                }
            }
        }
Beispiel #5
0
        public void TestCompare08()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("return a == b", "dummy", null,
                                           new KeyValuePair <string, Type>("a", typeof(object)),
                                           new KeyValuePair <string, Type>("b", typeof(object))
                                           );

                TestResult(g.dochunk(c, 1, 2), false);
                TestResult(g.dochunk(c, 2, 1), false);
                TestResult(g.dochunk(c, 2, 2), true);
                TestResult(g.dochunk(c, 2, (short)2), true);
                TestResult(g.dochunk(c, new TestOperator(1), 2), false);
                TestResult(g.dochunk(c, 2, new TestOperator(2)), false);
                object a = new object();
                TestResult(g.dochunk(c, a, a), true);
                TestResult(g.dochunk(c, "a", "a"), true);
                TestResult(g.dochunk(c, 3.0m, null), false);
                TestResult(g.dochunk(c, null, 3.0m), false);
                TestResult(g.dochunk(c, null, null), true);
            }
        }
Beispiel #6
0
        private void ReadScript(string path)
        {
            var tc   = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
            var data = System.IO.File.ReadAllText(tc + path);

            scriptChunk = lua.CompileChunk(data, "scriptChunk", null);
        }
Beispiel #7
0
        private void DoScript(Lua l, LuaGlobal g, string sScript)
        {
            Type type = typeof(RunLuaTests);

            using (Stream src = type.Assembly.GetManifestResourceStream(type, "CompTests." + sScript))
                using (StreamReader sr = new StreamReader(src))
                {
                    Console.WriteLine();
                    Console.WriteLine(new string('=', 60));
                    Console.WriteLine("= " + sScript);
                    Console.WriteLine();
                    try
                    {
                        g.DoChunk(l.CompileChunk(sr, sScript, Lua.StackTraceCompileOptions));
                    }
                    catch (Exception e)
                    {
                        if (e is LuaException)
                        {
                            Console.WriteLine("Line: {0}, Column: {1}", ((LuaException)e).Line, ((LuaException)e).Column);
                        }
                        Console.WriteLine("StackTrace:");
                        Console.WriteLine(LuaExceptionData.GetData(e).StackTrace);
                        throw;
                    }
                }
        }
Beispiel #8
0
 /// <summary>МЕТОД Тестирование кусков Lua</summary>
 /// <param name="pChunk">Код куска Lua</param>
 public void MET_TestLua(string pChunk)
 {
     PRI_Lua.CompileChunk(pChunk, new LuaCompileOptions {
         DebugEngine = new LuaStackTraceDebugger()
     });
     try
     {
         PRI_Lua.CompileChunk("return b * 2", new LuaCompileOptions(), new KeyValuePair <string, Type>("b", typeof(int)));
     }
     catch (Exception e)
     {
         MyGlo.PUB_Logger.Error(e, $"Ошибка формирования куска Lua в поле с VarId {PUB_Pole.PROP_VarId}," +
                                $" шаблона {PUB_Pole.PROP_FormShablon.PROP_Docum.PROP_ListShablon.PROP_Cod}," +
                                $"\n таблицы {PUB_Pole.PROP_FormShablon.PROP_TipProtokol.PROP_Shablon}");
     }
 }
 public void MainThread(ResourceManager resources, InstanceHelper instanceHelper)
 {
     resourceManager = resources;
     config          = resources.GetConfig(Name);
     if (EnsureConfigCorrect() == false)
     {
         resourceManager.SaveConfig(Name);
         resourceManager.SaveConfig("ArkDesktop.LayeredWindowManager");
         return;
     }
     ;
     manager = new LayeredWindowManager(resources);
     instanceHelper.AddControl("", manager);
     if (loadPosition == LoadPosition.InConfig)
     {
         if (config.Element("Script") == null)
         {
             MessageBox.Show("似乎没有加载到脚本,请联系配置包制作者");
             return;
         }
         luaScript = config.Element("Script").Value;
     }
     else
     {
         using (var sr = new System.IO.StreamReader(resourceManager.OpenRead("script.lua"))) luaScript = sr.ReadToEnd();
         if (luaScript == "")
         {
             MessageBox.Show("似乎没有加载到脚本,请联系配置包制作者", "QAQ");
             return;
         }
     }
     using (Lua lua = new Lua())
     {
         dynamic env   = lua.CreateEnvironment();
         LuaApi  api   = new LuaApi(this, lua, env);
         var     chunk = lua.CompileChunk(luaScript, "script.lua", new LuaCompileOptions {
             DebugEngine = LuaStackTraceDebugger.Default
         });
         manager.window.Click += (sender, e) => api.OnClick();
         var luaThread = new Thread(new ThreadStart(() =>
         {
             if (launchType == LaunchType.Positive)
             {
                 while (true)
                 {
                     try
                     {
                         env.dochunk(chunk);
                     }
                     catch (ThreadAbortException)
                     {
                         break;
                     }
                 }
                 catch (Exception e)
                 {
                     MessageBox.Show("发生异常:" + e.Message + "\n" + e.StackTrace);
                 }
             }
 private void LoadPackageFromResource(Assembly assembly, string resourcePath, string packageName)
 {
     using (Stream stream = assembly.GetManifestResourceStream(resourcePath))
     {
         using (StreamReader reader = new StreamReader(stream))
         {
             if (debug)
             {
                 global.DoChunk(lua.CompileChunk(reader, packageName, Lua.DefaultDebugEngine));
             }
             else
             {
                 global.DoChunk(reader, packageName);
             }
         }
     }
 }
Beispiel #11
0
        public bool LoadScripts()
        {
            ScriptEnvironment lastEnvironment = null, oldLastEnvironment = null;

            try
            {
                lastEnvironment       = ms_currentEnvironment;
                ms_currentEnvironment = this;

                oldLastEnvironment = LastEnvironment;
                LastEnvironment    = lastEnvironment;

                // load scripts defined in this resource
                foreach (var script in m_resource.ServerScripts)
                {
                    lock (m_luaEnvironment)
                    {
                        var chunk = ms_luaState.CompileChunk(Path.Combine(m_resource.Path, script), ms_luaCompileOptions);
                        m_luaEnvironment.DoChunk(chunk);
                        m_curChunks.Add(chunk);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                this.Log().Error(() => "Error creating script environment for resource " + m_resource.Name + ": " + e.Message, e);

                if (e.InnerException != null)
                {
                    this.Log().Error(() => "Inner exception: " + e.InnerException.Message, e.InnerException);
                }

                PrintLuaStackTrace(e);
            }
            finally
            {
                ms_currentEnvironment = lastEnvironment;
                LastEnvironment       = oldLastEnvironment;
            }

            return(false);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            //Minitouch.connect("localhost", 1111);
            //Minitouch.setPos(1, 100, 100);
            //Minitouch.press(1);

            using var lua = new Lua();
            var env = lua.CreateEnvironment();

            env.RegisterPackage("autopcr", typeof(Autopcr));
            env.RegisterPackage("minitouch", typeof(Minitouch));

            var chunk = lua.CompileChunk(File.ReadAllText("timeline.lua"), "timeline.lua", new LuaCompileOptions());

            Console.Write("pid>");
            var pid = int.Parse(Console.ReadLine());

            //var pid = 11892;
            hwnd = NativeFunctions.OpenProcess(NativeFunctions.PROCESS_ALL_ACCESS, false, pid);

            var tuple = AobscanHelper.Aobscan(hwnd, idcode, addr =>
            {
                var frame = TryGetInfo(hwnd, addr);
                if (frame.Item1 >= 0 && frame.Item1 < 1000 && frame.Item2 > 80 && frame.Item2 < 100)
                {
                    Console.WriteLine($"data found, frameCount = {frame.Item1}, limitTime = {frame.Item2}");
                    return(true);
                }
                return(false);
            });

            addr = tuple.Item1;

            Console.WriteLine($"addr = {addr:x}");

            Console.WriteLine();

            if (addr == -1)
            {
                Console.WriteLine("aobscan failed.");
                return;
            }

            seed_addr = AobscanHelper.Aobscan(hwnd, seed_code, addr =>
            {
                Console.WriteLine($"seed found.");
                return(true);
            }).Item1 - 0x90;

            chunk.Run(env);

            Console.WriteLine("script finished.");
            Minitouch.exit();

            Console.ReadLine();
        }
Beispiel #13
0
        /// <summary>
        /// 定时对字典数组中的某个字典进行检测,更新Lua脚本
        /// </summary>
        private void CheckDictLuaInfo(object source, ElapsedEventArgs e)
        {
            lock (dictLuaCache)
            {
                foreach (KeyValuePair <string, LuaExeInfo> kvLuaInfo in dictLuaCache)
                {
                    DateTime dateNew = File.GetLastWriteTime(kvLuaInfo.Key);
                    if (dateNew > kvLuaInfo.Value.dateLastWrite)
                    {
                        Func <string> code      = () => File.ReadAllText(kvLuaInfo.Key);
                        string        chunkName = Path.GetFileName(kvLuaInfo.Key);

                        LuaChunk c = lua.CompileChunk(code(), chunkName, false);
                        kvLuaInfo.Value.dateLastWrite = dateNew;
                        kvLuaInfo.Value.luaChunk      = c;
                    }
                }
            }
        }
Beispiel #14
0
        public void TestArithmetic09()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g  = l.CreateEnvironment();
                var c1 = l.CompileChunk("return a + b;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(int)), new KeyValuePair <string, Type>("b", typeof(TestOperator)));
                var c2 = l.CompileChunk("return a + b;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(object)));

                TestResult(g.DoChunk(c1, 1, new TestOperator(2)), new TestOperator(3));

                TestResult(g.DoChunk(c2, 1, new TestOperator(2)), new TestOperator(3));
                TestResult(g.DoChunk(c2, new TestOperator(2), 1), new TestOperator(3));
                TestResult(g.DoChunk(c2, new TestOperator(2), new TestOperator(1)), new TestOperator(3));
                TestResult(g.DoChunk(c2, new TestOperator(2), (short)1), new TestOperator(3));
                TestResult(g.DoChunk(c2, new TestOperator2(2), 1L), 3L);
                TestResult(g.DoChunk(c2, 2, new TestOperator2(1)), 3);
            }
        }
Beispiel #15
0
        public void TestArithmetic11()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g  = l.CreateEnvironment();
                var c1 = l.CompileChunk("return a + b;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(Nullable <int>)), new KeyValuePair <string, Type>("b", typeof(Nullable <int>)));
                var c2 = l.CompileChunk("return a + b;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(object)));

                TestResult(g.DoChunk(c1, 1, 2), 3);
                TestResult(g.DoChunk(c1, null, 2), NullResult);

                TestResult(g.DoChunk(c2, new Nullable <short>(1), new Nullable <short>(2)), (short)3);
                TestResult(g.DoChunk(c2, new Nullable <int>(1), new Nullable <int>(2)), 3);
                TestResult(g.DoChunk(c2, new Nullable <int>(1), new Nullable <short>(2)), 3);
                TestResult(g.DoChunk(c2, new Nullable <short>(1), (short)2), (short)3);
                TestResult(g.DoChunk(c2, new Nullable <int>(1), 2), 3);
                TestResult(g.DoChunk(c2, new Nullable <int>(1), (short)2), 3);
            }
        }
Beispiel #16
0
        public void TestArithmetic05()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g = l.CreateEnvironment();
                var c = l.CompileChunk("return 1 + a;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(string)));

                TestResult(g.DoChunk(c, "2"), 3);
                TestResult(g.DoChunk(c, "2.0"), 3.0);
            }
        }
Beispiel #17
0
        public void TestFunctions62()
        {
            using (var l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("print(a)", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                g.dochunk(c, 1);
                g.dochunk(c, "a");
            }
        }
Beispiel #18
0
            }             // proc Dispose

            #endregion

            #region -- Compile --------------------------------------------------------------

            protected virtual void Compile(Func <TextReader> open, KeyValuePair <string, Type>[] args)
            {
                lock (chunkLock)
                {
                    // clear the current chunk
                    Procs.FreeAndNil(ref chunk);

                    // recompile the script
                    using (var tr = open())
                        chunk = Lua.CompileChunk(tr, scriptId, compiledWithDebugger ? engine.debugOptions : null, args);
                }
            }             // proc Compile
Beispiel #19
0
 public void RequestClickEvent(string methodName)
 {
     clickMethod = methodName;
     if (methodName == "")
     {
         clickMethodChunk = null;
     }
     else
     {
         clickMethodChunk = lua.CompileChunk(methodName + "()", "script.lua", new LuaCompileOptions());
     }
 }
Beispiel #20
0
        public void TestArrayLength02()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("return #a;", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                TestResult(g.dochunk(c, "abc"), 3);
                TestResult(g.dochunk(c, new TestOperator(3)), 3);
                TestResult(g.dochunk(c, new TestOperator2(3)), 3);
            }
        }
Beispiel #21
0
 public void EventTest04()
 {
     using (Lua l = new Lua())
     {
         var g = l.CreateEnvironment();
         var c = l.CompileChunk(Lines(
                                    "local a : System.EventHandler = function(a, b) : void",
                                    "  print('Hallo');",
                                    "end;",
                                    "a()"), "dummy", Lua.DefaultDebugEngine);
         g.DoChunk(c);
     }
 }
Beispiel #22
0
        public void TestConvert08()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("return cast(int, a)", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                TestResult(g.dochunk(c, new LuaResult(2)), 2);
                TestResult(g.dochunk(c, new LuaResult((short)2)), 2);
                TestResult(g.dochunk(c, new LuaResult(ShortEnum.Zwei)), 2);
            }
        }
Beispiel #23
0
 public void EventTest04()
 {
     using (Lua l = new Lua())
     {
         var g = l.CreateEnvironment();
         var c = l.CompileChunk(Lines(
                                    "local a : System.EventHandler = function(a, b) : void",
                                    "  print('Hallo');",
                                    "end;",
                                    "a()"), "dummy", LuaDeskop.StackTraceCompileOptions);
         g.DoChunk(c);
     }
 }
Beispiel #24
0
        public void TestArithmetic10()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g = l.CreateEnvironment();
                var c = l.CompileChunk("return a + b;", "test.lua", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(object)));

                TestResult(g.DoChunk(c, ShortEnum.Eins, ShortEnum.Zwei), ShortEnum.Drei);
                TestResult(g.DoChunk(c, IntEnum.Eins, IntEnum.Zwei), IntEnum.Drei);
                TestResult(g.DoChunk(c, (short)1, IntEnum.Zwei), 3);
                TestResult(g.DoChunk(c, ShortEnum.Eins, 2), 3);
            }
        }
Beispiel #25
0
 public void EventTest05()
 {
     using (Lua l = new Lua())
     {
         l.PrintExpressionTree = Console.Out;
         var g = l.CreateEnvironment();
         var c = l.CompileChunk(Lines(
                                    "local a : System.EventHandler = function(a, b) : void",
                                    "  print('Hallo');",
                                    "end;",
                                    "a();"), "dummy", null);
         g.DoChunk(c);
     }
 }
Beispiel #26
0
        public void TestLogic10()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g = l.CreateEnvironment();
                var c = l.CompileChunk("if a then return true else return false end", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                TestResult(g.DoChunk(c, 1), true);
                TestResult(g.DoChunk(c, 0), true);
                TestResult(g.DoChunk(c, ShortEnum.Drei), true);
                TestResult(g.DoChunk(c, IntEnum.Null), true);
                TestResult(g.DoChunk(c, new object[] { null }), false);
            }
        }
Beispiel #27
0
        public void TestLogic12()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                var g = l.CreateEnvironment();
                var c = l.CompileChunk("return a and b", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)), new KeyValuePair <string, Type>("b", typeof(object)));

                TestResult(g.DoChunk(c, null, 10), NullResult);
                TestResult(g.DoChunk(c, false, false), false);
                TestResult(g.DoChunk(c, false, null), false);
                TestResult(g.DoChunk(c, 10, 20), 20);
                TestResult(g.DoChunk(c, new TestOperator(10), 20), 20);
            }
        }
Beispiel #28
0
        public void TestConvert04()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("return cast(string, a)", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                TestResult(g.dochunk(c, 'a'), "a");
                TestResult(g.dochunk(c, 1), "1");
                TestResult(g.dochunk(c, ShortEnum.Eins), "Eins");
                TestResult(g.dochunk(c, null), "");
                TestResult(g.dochunk(c, new object()), "System.Object");
            }
        }
Beispiel #29
0
        public void CodePlexExample5()
        {
            using (Lua l = new Lua())
            {
                LuaChunk c = l.CompileChunk("return a;", "test.lua", null);

                var g1 = l.CreateEnvironment();
                var g2 = l.CreateEnvironment();

                g1["a"] = 2;
                g2["a"] = 4;

                Console.WriteLine((int)(g1.DoChunk(c)[0]) + (int)(g2.DoChunk(c)[0]));
            }
        }
Beispiel #30
0
        public void TestConvert06()
        {
            using (Lua l = new Lua())
            {
                l.PrintExpressionTree = Console.Out;
                dynamic g = l.CreateEnvironment();
                var     c = l.CompileChunk("return cast(int, a)", "dummy", null, new KeyValuePair <string, Type>("a", typeof(object)));

                TestResult(g.dochunk(c, "1"), 1);
                TestResult(g.dochunk(c, ShortEnum.Eins), 1);
                TestResult(g.dochunk(c, '1'), 49);
                TestResult(g.dochunk(c, "1.2"), 1);
                TestResult(g.dochunk(c, null), 0);
            }
        }
Beispiel #31
0
		public void Exception01()
		{
			using (Lua l = new Lua())
			{
				var g = l.CreateEnvironment();
				try
				{
					g.DoChunk(l.CompileChunk("\nNull(a, a);", "test.lua", LuaDeskop.StackTraceCompileOptions, new KeyValuePair<string, Type>("a", typeof(int))), 1);
				}
				catch (Exception e)
				{
					LuaExceptionData d = LuaExceptionData.GetData(e);
					Assert.IsTrue(d[2].LineNumber == 2);
				}
			}
		} // proc Exception01
Beispiel #32
0
		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
			using (Lua l = new Lua())
			{
				var t = new LuaTable();
				var c = l.CompileChunk(
					String.Join(Environment.NewLine,
						"local v1 = 2;",
						"local v2 = 4;",
						"function f()",
						"  return v1 + v2;",
						"end;",
						"return f();"), "test", null);
				var r = c.Run(t);
				txtResult.Text = String.Format("Test: v1=[{0}], v2=[{1}], r={2}", Lua.RtGetUpValue(t.GetMemberValue("f") as Delegate, 1), Lua.RtGetUpValue(t.GetMemberValue("f") as Delegate, 2), r.ToInt32());
			}
		}
Beispiel #33
0
		public void Exception02()
		{
			using (Lua l = new Lua())
			{
				var g = l.CreateEnvironment();
				try
				{
					g.DoChunk(l.CompileChunk("math.abs(-1 / a).A();", "test.lua", LuaDeskop.StackTraceCompileOptions, new KeyValuePair<string, Type>("a", typeof(int))), 1);
				}
				catch (Exception e)
				{
					LuaExceptionData d = LuaExceptionData.GetData(e);
					Debug.Print("Error: {0}", e.Message);
					Debug.Print("Error at:\n{0}", d.StackTrace);
					Assert.IsTrue(d[2].LineNumber == 1); //  && d[2].ColumnNumber == 18 in release this is one
				}
			}
		} // proc Exception01
Beispiel #34
0
		static void Main(string[] args)
		{
			Console.Write(TestAsync().Result);
			using (Lua l = new Lua())
			{
				var t = new LuaTable();
				var c = l.CompileChunk(
					String.Join(Environment.NewLine,
						"local v1 = 2;",
						"local v2 = 4;",
						"function f()",
						"  return v1 + v2;",
						"end;",
						"return f();"), "test", null);
				var r = c.Run(t);
				Console.WriteLine("Test: v1=[{0}], v2=[{1}], r={2}", Lua.RtGetUpValue(t.GetMemberValue("f") as Delegate, 1), Lua.RtGetUpValue(t.GetMemberValue("f") as Delegate, 2), r.ToInt32());
			}

			//LinqTest2();
			Console.ReadKey();
		}
Beispiel #35
0
 public void EventTest04()
 {
     using (Lua l = new Lua())
       {
         var g = l.CreateEnvironment();
         var c = l.CompileChunk(Lines(
             "local a : System.EventHandler = function(a, b) : void",
             "  print('Hallo');",
             "end;",
             "a()"), "dummy", LuaDeskop.StackTraceCompileOptions);
         g.DoChunk(c);
       }
 }
Beispiel #36
0
        public void TestFunctions62()
        {
            using (Lua l = new Lua())
              {
            l.PrintExpressionTree = Console.Out;
            dynamic g = l.CreateEnvironment();
            var c = l.CompileChunk("print(a)", "dummy", null, new KeyValuePair<string, Type>("a", typeof(object)));

            g.dochunk(c, 1);
            g.dochunk(c, "a");
              }
        }
Beispiel #37
0
    public void CodePlexExample5()
    {
      using (Lua l = new Lua())
      {
        LuaChunk c = l.CompileChunk("return a;", "test.lua", null);

        var g1 = l.CreateEnvironment();
        var g2 = l.CreateEnvironment();

        g1["a"] = 2;
        g2["a"] = 4;

        Console.WriteLine((int)(g1.DoChunk(c)[0]) + (int)(g2.DoChunk(c)[0]));
      }
    }
        public bool Create()
        {
            ScriptEnvironment lastEnvironment = null, oldLastEnvironment = null;

            try
            {
                if (ms_luaState == null)
                {
                    ms_luaState = new Lua();

                    //ms_luaDebug = new LuaStackTraceDebugger();
                    ms_luaDebug = null;

                    if (Resource.Manager.Configuration.ScriptDebug)
                    {
                        ms_luaDebug = new LuaStackTraceDebugger();
                    }

                    ms_luaCompileOptions = new LuaCompileOptions();
                    ms_luaCompileOptions.DebugEngine = ms_luaDebug;

                    ms_initChunks = new []
                    {
                        ms_luaState.CompileChunk("system/MessagePack.lua", ms_luaCompileOptions),
                        ms_luaState.CompileChunk("system/dkjson.lua", ms_luaCompileOptions),
                        ms_luaState.CompileChunk("system/resource_init.lua", ms_luaCompileOptions)
                    };
                }

                m_luaEnvironment = ms_luaState.CreateEnvironment();

                foreach (var func in ms_luaFunctions)
                {
                    //m_luaEnvironment[func.Key] = Delegate.CreateDelegate
                    var parameters = func.Value.GetParameters()
                                    .Select(p => p.ParameterType)
                                    .Concat(new Type[] { func.Value.ReturnType })
                                    .ToArray();

                    var delegType = Expression.GetDelegateType
                    (
                        parameters
                    );

                    var deleg = Delegate.CreateDelegate
                    (
                        delegType,
                        null,
                        func.Value
                    );

                    var expParameters = parameters.Take(parameters.Count() - 1).Select(a => Expression.Parameter(a)).ToArray();

                    var pushedEnvironment = Expression.Variable(typeof(PushedEnvironment));

                    Expression<Func<PushedEnvironment>> preFunc = () => PushEnvironment(this);
                    Expression<Action<PushedEnvironment>> postFunc = env => env.PopEnvironment();

                    Expression body;

                    if (func.Value.ReturnType.Name != "Void")
                    {
                        var retval = Expression.Variable(func.Value.ReturnType);

                        body = Expression.Block
                        (
                            func.Value.ReturnType,
                            new[] { retval, pushedEnvironment },

                            Expression.Assign
                            (
                                pushedEnvironment,
                                Expression.Invoke(preFunc)
                            ),

                            Expression.Assign
                            (
                                retval,
                                Expression.Call(func.Value, expParameters)
                            ),

                            Expression.Invoke(postFunc, pushedEnvironment),

                            retval
                        );
                    }
                    else
                    {
                        body = Expression.Block
                        (
                            func.Value.ReturnType,
                            new[] { pushedEnvironment },

                            Expression.Assign
                            (
                                pushedEnvironment,
                                Expression.Invoke(preFunc)
                            ),

                            Expression.Call(func.Value, expParameters),

                            Expression.Invoke(postFunc, pushedEnvironment)
                        );
                    }

                    var lambda = Expression.Lambda(delegType, body, expParameters);

                    m_luaEnvironment[func.Key] = lambda.Compile();
                }

                InitHandler = null;

                /*m_luaNative = LuaL.LuaLNewState();
                LuaL.LuaLOpenLibs(m_luaNative);

                LuaLib.LuaNewTable(m_luaNative);
                LuaLib.LuaSetGlobal(m_luaNative, "luanet");

                InitHandler = null;

                m_luaState = new NLua.Lua(m_luaNative);*/

                lock (m_luaEnvironment)
                {
                    lastEnvironment = ms_currentEnvironment;
                    ms_currentEnvironment = this;

                    oldLastEnvironment = LastEnvironment;
                    LastEnvironment = lastEnvironment;

                    // load global data files
                    foreach (var chunk in ms_initChunks)
                    {
                        m_luaEnvironment.DoChunk(chunk);
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                this.Log().Error(() => "Error creating script environment for resource " + m_resource.Name + ": " + e.Message, e);

                if (e.InnerException != null)
                {
                    this.Log().Error(() => "Inner exception: " + e.InnerException.Message, e.InnerException);
                }

                PrintLuaStackTrace(e);
            }
            finally
            {
                ms_currentEnvironment = lastEnvironment;
                LastEnvironment = oldLastEnvironment;
            }

            return false;
        }
Beispiel #39
0
 public void EventTest05()
 {
     using (Lua l = new Lua())
       {
     l.PrintExpressionTree = Console.Out;
         var g = l.CreateEnvironment();
         var c = l.CompileChunk(Lines(
             "local a : System.EventHandler = function(a, b) : void",
             "  print('Hallo');",
             "end;",
             "a();"), "dummy", null);
         g.DoChunk(c);
       }
 }
Beispiel #40
-1
		private void DoScript(Lua l, LuaGlobal g, string sScript)
		{
			Type type = typeof(RunLuaTests);
			using (Stream src = type.Assembly.GetManifestResourceStream(type, "CompTests." + sScript))
			using (StreamReader sr = new StreamReader(src))
			{
				Console.WriteLine();
				Console.WriteLine(new string('=', 60));
				Console.WriteLine("= " + sScript);
				Console.WriteLine();
				try
				{
					g.DoChunk(l.CompileChunk(sr, sScript, LuaDeskop.StackTraceCompileOptions));
				}
				catch (Exception e)
				{
					if (e is LuaException)
						Console.WriteLine("Line: {0}, Column: {1}", ((LuaException)e).Line, ((LuaException)e).Column);
					Console.WriteLine("StackTrace:");
					Console.WriteLine(LuaExceptionData.GetData(e).StackTrace);
					throw;
				}
			}
		}