Example #1
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();
                }
            }
        }
Example #2
0
        public LuaEngine(IServiceProvider sp, string name)
            : base(sp, name)
        {
            // create the state
            this.propertyScriptCount = new SimpleConfigItemProperty <int>(this, "tw_luaengine_scripts", "Skripte", "Lua-Engine", "Anzahl der aktiven Scripte.", "{0:N0}", 0);

            // create the lists
            this.scripts = new DEList <LuaScript>(this, "tw_scripts", "Scriptlist");
            this.globals = new DEList <LuaAttachedGlobal>(this, "tw_globals", "Attached scripts");

            // Register the service
            var sc = sp.GetService <IServiceContainer>(true);

            sc.AddService(typeof(IDELuaEngine), this);

            // register context extensions
            LuaType.RegisterTypeExtension(typeof(HttpResponseHelper));

            // create the debug options
            debugHook                = new LuaEngineTraceLineDebugger(this);
            debugOptions             = new LuaCompileOptions();
            debugOptions.DebugEngine = debugHook;

            // update lua runtime
            sp.GetService <DEServer>(true).UpdateLuaRuntime(lua);
        }         // ctor
Example #3
0
        public static void Init(string title, uint scrw, uint scrh, bool fixedDT = false)
        {
            ScrW    = scrw;
            ScrH    = scrh;
            FixedDT = fixedDT;

            Window = new RenderWindow(new VideoMode(scrw, scrh), title);
            Window.SetVerticalSyncEnabled(false);
            Window.SetFramerateLimit(60);
            Window.SetKeyRepeatEnabled(false);

            Clock = new Clock();

            LuaEngine         = new Lua();
            LuaEnvironment    = LuaEngine.CreateEnvironment();
            LuaCompileOptions = new LuaCompileOptions();

            ResourceManager.Init();
            Screen.Init();

            World = new World();

            if (OnInit != null)
            {
                OnInit();
            }
        }
Example #4
0
 public void Setup()
 {
     lua                 = new Lua();
     luaEnv              = lua.CreateEnvironment();
     options             = new LuaCompileOptions();
     options.DebugEngine = new LuaStackTraceDebugger();
 }
Example #5
0
        /// <summary>СОБЫТИЕ Нажали на кнопку Тестирование кусков Lua</summary>
        private void PART_ButtonTest_Click(object sender, RoutedEventArgs e)
        {
            Lua _Lua = new Lua();
            LuaCompileOptions _Options = new LuaCompileOptions();

            _Options.DebugEngine = new LuaStackTraceDebugger();
            try
            {
                _Lua.CompileChunk(PART_FCTextBox.Text, "Test.lua", _Options);
                MET_LogAdd("Успех");
            }
            catch (LuaParseException ex)
            {
                MET_LogAdd($"Ошибка в строке {ex.Line}: {ex.Message}");
            }
            catch (Exception er)
            {
                MET_LogAdd($"Ошибка: {er.Message}");
            }
        }
Example #6
0
        /// <summary>Parses the chunk to an function.</summary>
        /// <param name="runtime">Binder</param>
        /// <param name="options">Compile options for the script.</param>
        /// <param name="lHasEnvironment">Creates the _G parameter.</param>
        /// <param name="code">Lexer for the code.</param>
        /// <param name="typeDelegate">Type for the delegate. <c>null</c>, for an automatic type</param>
        /// <param name="returnType">Defines the return type of the chunk.</param>
        /// <param name="args">Arguments of the function.</param>
        /// <returns>Expression-Tree for the code.</returns>
        public static LambdaExpression ParseChunk(Lua runtime, LuaCompileOptions options, bool lHasEnvironment, LuaLexer code, Type typeDelegate, Type returnType, IEnumerable<KeyValuePair<string, Type>> args)
        {
            List<ParameterExpression> parameters = new List<ParameterExpression>();
            if (returnType == null)
                returnType = typeof(LuaResult);
            var globalScope = new GlobalScope(runtime, options, returnType, returnType == typeof(LuaResult) ? Expression.Property(null, Lua.ResultEmptyPropertyInfo) : null);

            // Registers the global LuaTable
            if (lHasEnvironment)
                parameters.Add(globalScope.RegisterParameter(typeof(LuaTable), csEnv));

            if (args != null)
            {
                foreach (var c in args)
                    parameters.Add(globalScope.RegisterParameter(c.Value, c.Key)); // Add alle arguments
            }

            // Get the first token
            if (code.Current == null)
                code.Next();

            // Get the name for the chunk and clean it from all unwanted chars
            string sChunkName = CreateNameFromFile(code.Current.Start.FileName);
              if ((globalScope.EmitDebug & LuaDebugLevel.RegisterMethods) == LuaDebugLevel.RegisterMethods)
                sChunkName = Lua.RegisterUniqueName(sChunkName);

            // Create the block
            ParseBlock(globalScope, code);

            if (code.Current.Typ != LuaToken.Eof)
                throw ParseError(code.Current, Properties.Resources.rsParseEof);

            // Create the function
            return typeDelegate == null ?
                Expression.Lambda(globalScope.ExpressionBlock, sChunkName, parameters) :
                Expression.Lambda(typeDelegate, globalScope.ExpressionBlock, sChunkName, parameters);
        }
Example #7
0
 /// <summary>Global parse-scope</summary>
 /// <param name="runtime">Runtime and binder of the global scope.</param>
 /// <param name="options"></param>
 /// <param name="returnType"></param>
 /// <param name="returnDefaultValue"></param>
 public GlobalScope(Lua runtime, LuaCompileOptions options, Type returnType, Expression returnDefaultValue)
     : base(null, returnType, returnDefaultValue)
 {
     this.runtime = runtime;
     this.options = options;
     this.debug = options.DebugEngine == null ? LuaDebugLevel.None : options.DebugEngine.Level;
 }
Example #8
0
        public static void LuaThread()
        {
            if (watcher == null)
            {
                Watch();
            }


            App.c = Chroma.Instance;
            App.c.Initialize();
            App.c.DeviceAccess += C_DeviceAccess;
            App.NewScriptsContext();
            // WE NEED TO ENSURE CHROMA IS INITIALISED
            callbacks = new List <dynamic>();

            var ms_luaDebug          = new LuaStackTraceDebugger();
            var ms_luaCompileOptions = new LuaCompileOptions();

            ms_luaCompileOptions.DebugEngine = ms_luaDebug;
            scriptThreads = new Collection <Thread>();

            string path = @"%appdata%\ChromaSync";

            path = Environment.ExpandEnvironmentVariables(path);

            string scriptsPath  = Path.Combine(path, "scripts");
            string packagesPath = Path.Combine(path, "packages");

            if (!Directory.Exists(scriptsPath))
            {
                Directory.CreateDirectory(scriptsPath);
            }


            // Todo: Get all scripts including the packages
            var files = Directory.GetFiles(path, "*.lua", SearchOption.AllDirectories);

            foreach (string st in files)
            {
                var      v        = RegistryKeeper.GetValue(st);
                MenuItem menuItem = new MenuItem(Path.GetFileName(st));
                menuItem.Name   = Path.GetFileName(st);
                menuItem.Tag    = st;
                menuItem.Click += MenuItem_Click;
                if (!st.Contains("\\ChromaSync\\packages\\"))
                {
                    App.scriptsMenu.MenuItems.Add(menuItem);
                }
                if (v.Equals("True"))
                {
                    menuItem.Checked = true;
                    scriptThreads.Add(
                        new Thread(() =>
                    {
                        using (Lua l = new Lua())
                        {
                            LuaGlobalPortable g = l.CreateEnvironment();
                            dynamic dg          = g;
                            dg.DebugLua         = new Func <object, bool>(debug);
                            dg.ConvertInt       = new Func <object, int>(convertInt);
                            dg.NewCustom        = new Func <string, Color, object>(newCustom);
                            dg.IntToByte        = new Func <int, byte>(IntToByte);
                            dg.Headset          = Headset.Instance;
                            dg.Keyboard         = Keyboard.Instance;
                            dg.Mouse            = Mouse.Instance;
                            dg.Keypad           = Keypad.Instance;
                            dg.Mousepad         = Mousepad.Instance;

                            dg.RegisterForEvents = new Func <string, object, bool>(registerEvents);
                            debug("starting Lua script: " + st);
                            try
                            {
                                LuaChunk compiled = l.CompileChunk(st, ms_luaCompileOptions);
                                var d             = g.DoChunk(compiled);
                            }
                            catch (LuaException e)
                            {
                                App.Log.Error(e);
                            }
                            catch (Exception e)
                            {
                                App.Log.Info(e);
                                Thread.ResetAbort();
                            }
                        }
                    }));
                    scriptThreads.Last().Start();
                }
            }
        }
Example #9
0
 public LuaBridge()
 {
     compiler = new Lua();
     lc = new LuaCompileOptions();
 }
Example #10
0
        public static void LuaThread()
        {
            if (watcher == null)
            {
                Watch();
            }

            // WE NEED TO ENSURE CHROMA IS INITIALISED
            var c = Chroma.Instance;

            callbacks = new List <dynamic>();
            var ms_luaDebug          = new LuaStackTraceDebugger();
            var ms_luaCompileOptions = new LuaCompileOptions();

            ms_luaCompileOptions.DebugEngine = ms_luaDebug;
            scriptThreads = new Collection <Thread>();
            EventHook.MouseHook.MouseAction += new EventHandler(Event);

            string path = @"%appdata%\ChromaSync";

            path = Environment.ExpandEnvironmentVariables(path);

            path = Path.Combine(path, "scripts");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            foreach (string st in Directory.GetFiles(path, "*_main.lua", SearchOption.AllDirectories))
            {
                scriptThreads.Add(
                    new Thread(() =>
                {
                    using (Lua l = new Lua())
                    {
                        LuaGlobalPortable g = l.CreateEnvironment();
                        dynamic dg          = g;
                        dg.DebugLua         = new Func <object, bool>(debug);
                        dg.ConvertInt       = new Func <JValue, int>(convertInt);
                        dg.NewCustom        = new Func <string, Color, object>(newCustom);
                        dg.IntToByte        = new Func <int, byte>(IntToByte);
                        dg.Headset          = Headset.Instance;
                        dg.Keyboard         = Keyboard.Instance;
                        dg.Mouse            = Mouse.Instance;
                        dg.Keypad           = Keypad.Instance;
                        dg.Mousepad         = Mousepad.Instance;

                        dg.RegisterForEvents = new Func <string, object, bool>(registerEvents);
                        debug("starting Lua script: " + st);
                        try
                        {
                            LuaChunk compiled = l.CompileChunk(st, ms_luaCompileOptions);
                            var d             = g.DoChunk(compiled);
                        }
                        catch (LuaException e)
                        {
                            debug(e.FileName + ": " + e.Line + ": " + e.Message);
                        } catch (Exception e)
                        {
                            debug(e.Message);
                        }
                    }
                }));
                scriptThreads.Last().Start();
            }
        }
Example #11
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 <LuaGlobal>();

                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);
        }
Example #12
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;
        }