Example #1
0
        /// <summary>
        /// Processes an HTTP Web request for a #Lua doc
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            // Create a new environment and add a table 'web' that has access to the HttpObjects
            LuaTypes.LuaTable env = LuaRuntime.CreateGlobalEnviroment();

            LuaTypes.LuaTable Web = new SharpLua.LuaTypes.LuaTable();
            Web.SetNameValue("context", SharpLua.ObjectToLua.ToLuaValue(context));
            Web.SetNameValue("response", SharpLua.ObjectToLua.ToLuaValue(context.Response));
            Web.SetNameValue("request", SharpLua.ObjectToLua.ToLuaValue(context.Request));
            Web.SetNameValue("application", SharpLua.ObjectToLua.ToLuaValue(context.Application));
            Web.SetNameValue("session", SharpLua.ObjectToLua.ToLuaValue(context.Session));
            Web.SetNameValue("filepath", SharpLua.ObjectToLua.ToLuaValue(context.Request.PhysicalPath));

            env.SetNameValue("web", Web);

            try
            {
                LuaRuntime.RunFile(context.Request.PhysicalPath, env);
            }
            catch (Exception e)
            {
                context.Response.Write("<h1>Error Loading #Lua File " + context.Request.PhysicalPath + "</h1><br />");
                context.Response.Write("<br /> <font color='red'>");
                context.Response.Write(e.ToString().Replace("\n", "<br />"));
                context.Response.Write("</font>");
            }
        }
Example #2
0
        public static LuaValue DoFile(LuaValue[] values)
        {
            LuaString file       = values[0] as LuaString;
            LuaTable  enviroment = LuaRuntime.GlobalEnvironment;

            return(LuaRuntime.RunFile(file.Text, enviroment));
        }
Example #3
0
        public static LuaValue OpenFile(LuaValue[] values)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "Lua files|*.lua|SharpLua files|*.slua|wLua files|*.wlua|All Files|*.*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine("Loading file '" + Path.GetFileName(ofd.FileName) + "'...");
                return(LuaRuntime.RunFile(ofd.FileName, LuaRuntime.GlobalEnvironment));
            }
            else
            {
                return(LuaNil.Nil);
            }
        }
        public MechJebModuleAutom8(MechJebCore core)
            : base(core)
        {
            instance = this;
            luaEnv   = LuaRuntime.CreateGlobalEnviroment();
            mechjeb  = new LuaTable();
            core.registerLuaMembers(mechjeb);
            luaEnv.SetNameValue("mechjeb", mechjeb);
            luaEnv.SetNameValue("vessel", ObjectToLua.ToLuaValue(vesselState));

            if (KSP.IO.File.Exists <MuMechJeb>("autorun.lua"))
            {
                try
                {
                    LuaRuntime.GlobalEnvironment = luaEnv;
                    LuaRuntime.RunFile("autorun.lua", luaEnv);
                }
                catch (Exception e)
                {
                    A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
                    luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
                }
            }
        }
Example #5
0
        /// <summary>
        /// A REPL (Read, Eval, Print, Loop function) for #Lua
        /// </summary>
        /// <param name="args">Application startup args</param>
        public static void Main(string[] args)
        {
            bool GoInteractive = true;

            // Create global variables
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            LuaRuntime.PrintBanner();
            LuaRuntime.RegisterModule(typeof(TestModule));
            LuaRuntime.RegisterModule(typeof(TestModule2));

            // how to handle errors
#if DEBUG
            LuaRuntime.SetVariable("DEBUG", true);
#else
            LuaRuntime.SetVariable("DEBUG", false);
#endif

            Prompt = "> ";

            LuaRuntime.GetLua().NewTable("arg");
            LuaTable t = LuaRuntime.GetLua().GetTable("arg");
            for (int i = 0; i < args.Length; i++)
            {
                t[i] = args[i];
            }

            // check command line args
            if (args.Length > 0)
            {
                string file = args[0];
                if (File.Exists(file))
                {
                    try
                    {
                        LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(file));
                        LuaRuntime.RunFile(file);
                        // it loaded successfully
                        if (args.Length > 1) // possibly interactive mode after
                        {
                            Console.WriteLine("Loaded file '" + Path.GetFileName(file) + "'");
                        }
                    }
                    catch (Exception error)
                    {
                        Console.WriteLine(error.Message);
                    }
                    //Console.ReadKey(true);
                    //return;
                    // instead, go to interactive
                }
                else
                {
                    Console.WriteLine(file + " not found.");
                }
            }

            // check for interactive mode
            foreach (string arg in args)
            {
                if (arg.ToUpper() == "-I")
                {
                    GoInteractive = true;
                }
            }

            if (args.Length == 0)
            {
                GoInteractive = true;
            }

            if (GoInteractive)
            {
                while (true)
                {
                    Console.Write(Prompt);
                    string line = Console.ReadLine();

                    if (line == "quit" || line == "exit" || line == "bye")
                    {
                        break;
                    }
                    else
                    {
                        try
                        {
                            object[] v = LuaRuntime.Run(line);
                            if (v == null || v.Length == 0)
                            {
                                Console.WriteLine("=> [no returned value]");
                            }
                            else
                            {
                                Console.Write("=> ");
                                for (int i = 0; i < v.Length; i++)
                                {
                                    if (v[i] == null)
                                    {
                                        Console.WriteLine("<nil>");
                                    }
                                    else
                                    {
                                        Console.Write(v[i].ToString() + (i != v.Length - 1 ? ", " : ""));
                                    }
                                }
                                Console.WriteLine();
                            }
                        }
                        catch (LuaSourceException ex)
                        {
                            for (int i = 0; i < ex.Column; i++)
                            {
                                Console.Write(" ");
                            }

                            // Offset for prompt
                            for (int i = 0; i < Prompt.Length - 1; i++)
                            {
                                Console.Write(" ");
                            }

                            Console.WriteLine("^");
                            Console.WriteLine(ex.GenerateMessage("<stdin>"));
                        }
                        catch (Exception error)
                        {
                            // TODO: show lua script traceback
                            // Possible fix... this isn't safe though.

                            //Console.WriteLine(error.Message);
                            // doesnt work :(
                            //LuaRuntime.Run("pcall(function() print(debug.traceback()) end)");
                            //Console.WriteLine();

                            object dbg = LuaRuntime.GetVariable("DEBUG");

                            if ((dbg is bool && (bool)dbg == true) || dbg is int == false)
                            {
                                Console.WriteLine(error.ToString());
                            }
                            else
                            {
                                Console.WriteLine("Error: " + error.Message);
                            }
                            LuaRuntime.SetVariable("LASTERROR", error);
                        }
                    }
                }
            }
        }
Example #6
0
        /// <summary>
        /// A REPL (Read, Eval, Print, Loop function) for #Lua
        /// </summary>
        /// <param name="args">Application startup args</param>
        public static void Main(string[] args)
        {
            // TODO: Better arg parsing/checking, make it more like the C lua

            bool GoInteractive = true;

            // Create global variables
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            //sw.Stop();
            //Console.WriteLine(sw.ElapsedMilliseconds);

#if DEBUG
#if true
            LuaRuntime.RegisterModule(typeof(TestModule));
            LuaRuntime.RegisterModule(typeof(TestModule2));
#endif

            // how to handle errors
            //LuaRuntime.SetVariable("DEBUG", true);
            LuaRuntime.SetVariable("DEBUG", false);
            // We don't need the C# traceback.
            // All it is is [error]
            //     at LuaInterface.ThrowErrorFromException
            //     [...]
            // Which we don't need
#else
            LuaRuntime.SetVariable("DEBUG", false);
#endif

            Prompt = "> ";

            bool wasSetInteract = false;
            bool wasFileRun     = false;
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                if (arg.ToUpper() == "-I")
                {
                    GoInteractive  = true;
                    wasSetInteract = true;
                }
                else if (arg.ToUpper() == "-NOI")
                {
                    GoInteractive = false;
                }
                else if (arg.Substring(0, 2).ToLower() == "-l")
                {
                    if (arg.Length == 2)
                    {
                        string lib = args[++i];
                        LuaRuntime.Require(lib);
                    }
                    else
                    {
                        string lib = arg.Substring(2);
                        LuaRuntime.Require(lib);
                    }
                }
                else if (arg.ToLower() == "-e")
                {
                    if (wasSetInteract == false)
                    {
                        GoInteractive = true;
                    }

                    LuaRuntime.Run(args[++i]);

                    if (wasSetInteract == false)
                    {
                        GoInteractive = false;
                    }
                    wasFileRun = true;
                }
                else if (arg == "--")
                {
                    break;
                }
                else
                {
                    LuaTable t  = LuaRuntime.GetLua().NewTable("arg");
                    int      i3 = 1;
                    if (args.Length > i + 1)
                    {
                        for (int i2 = i + 1; i2 < args.Length; i2++)
                        {
                            t[i3++] = args[i2];
                        }
                    }

                    t[-1]  = System.Windows.Forms.Application.ExecutablePath;
                    t["n"] = t.Keys.Count;

                    if (File.Exists(args[i]))
                    {
                        LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(args[i]));
                    }
                    else
                    {
                        LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath));
                    }
                    LuaRuntime.RunFile(args[i]);

                    if (wasSetInteract == false)
                    {
                        GoInteractive = false;
                    }

                    wasFileRun = true;
                    break;
                }
            }


            /*
             * // check command line args
             * if (args.Length > 0)
             * {
             *  string file = args[0];
             *  if (File.Exists(file))
             *  {
             *      try
             *      {
             *          LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(file));
             *          LuaRuntime.RunFile(file);
             *          // it loaded successfully
             *          if (args.Length > 1 && args[1].ToUpper() != "-NOI") // possibly interactive mode after
             *              Console.WriteLine("Loaded file '" + Path.GetFileName(file) + "'");
             *      }
             *      catch (Exception error)
             *      {
             *          Console.WriteLine(error.Message);
             *      }
             *      //Console.ReadKey(true);
             *      //return;
             *      // instead, go to interactive
             *  }
             *  else
             *  {
             *      Console.WriteLine(file + " not found.");
             *  }
             * }
             */

            if (args.Length == 0)
            {
                GoInteractive = true;
            }

            if (GoInteractive)
            {
                if (args.Length == 0 || wasFileRun == false)
                {
                    LuaRuntime.PrintBanner();
                }
                LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(typeof(Program).Assembly.Location));
                while (true)
                {
                    Console.Write(Prompt);
                    string line = Console.ReadLine();

                    if (line == "quit" || line == "exit" || line == "bye")
                    {
                        break;
                    }
                    else
                    {
                        try
                        {
                            object[] v = LuaRuntime.GetLua().DoString(line, "<stdin>");
                            if (v == null || v.Length == 0)
#if DEBUG
                            { Console.WriteLine("=> [no returned value]"); }
#else
                            {; }
#endif
                            else
                            {
                                Console.Write("=> ");
                                for (int i = 0; i < v.Length; i++)
                                {
                                    if (v[i] == null)
                                    {
                                        Console.WriteLine("<nil>");
                                    }
                                    else
                                    {
                                        Console.Write(v[i].ToString() + (i != v.Length - 1 ? ", " : ""));
                                    }
                                }
                                Console.WriteLine();
                            }
                        }
Example #7
0
        public static void RegisterFunctions(LuaTable module)
        {
            // cpath -> cspath?
            module.SetNameValue("cpath", new LuaString(".\\?;.\\?.dll;.\\?.exe"));
            module.SetNameValue("path", new LuaString(".\\?;.\\?.lua;.\\?.slua;.\\?.wlua;" + System.Environment.GetEnvironmentVariable("LUA_PATH")));
            module.SetNameValue("bpath", new LuaString(".\\?;.\\?.luac;.\\?.out;.\\?.sluac"));
            module.SetNameValue("loaded", new LuaTable());
            module.SetNameValue("preload", new LuaTable());
            module.Register("seeall", SeeAll);

            // Load package loader functions
            LuaTable loaderfunctions = new LuaTable();

            loaderfunctions.Register("PreloadSearcher", new LuaFunc(delegate(LuaValue[] args) {
                LuaTable t = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("preload") as LuaTable;
                string mod = (args[0] as LuaString).Text;
                LuaValue v = t.GetValue(mod);
                if (v != null && v != LuaNil.Nil)
                {
                    return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, v as LuaTable }));
                }
                else
                {
                    return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
                }
            }));

            loaderfunctions.Register("PathSearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("path").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            LuaTable m = new LuaTable();
                            m.AddValue(LuaRuntime.RunFile(fn, LuaRuntime.GlobalEnvironment));
                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, LuaRuntime.GlobalEnvironment.GetValue(Path.GetFileNameWithoutExtension(fn)) }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));

            loaderfunctions.Register("CSPathSearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("cpath").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            Console.WriteLine("Loading file '" + fn + "'...");
                            string[] modules = ExternalLibraryLoader.Load(fn);
                            LuaTable t       = LuaRuntime.GlobalEnvironment.GetValue(modules[0]) as LuaTable;

                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, t }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));
            loaderfunctions.Register("BinarySearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("bpath").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            LuaTable m = new LuaTable();
                            bool isBreak;
                            m.AddValue((Serializer.Deserialize(fn) as AST.Chunk).Execute(LuaRuntime.GlobalEnvironment, out isBreak));
                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, LuaRuntime.GlobalEnvironment.GetValue(Path.GetFileNameWithoutExtension(fn)) }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));
            module.SetNameValue("loaders", loaderfunctions);
            module.Register("loadlib", new LuaFunc((LuaValue[] args) =>
            {
                return(args[0]);
            }));
        }