Ejemplo n.º 1
0
        void Update()
        {
            while (server.Server.IsBound && server.Pending())
            {
                SocketStateObject newConn = new SocketStateObject();
                newConn.socket = server.AcceptSocket();
                connections.Add(newConn);
            }

            List <SocketStateObject> cleanup = new List <SocketStateObject>();

            byte[] sendData;
            lock (this)
            {
                sendData  = Encoding.UTF8.GetBytes(sendCache.ToString());
                sendCache = new StringBuilder();
            }

            LuaRuntime.GlobalEnvironment = luaEnv;
            foreach (SocketStateObject client in connections)
            {
                if (!client.socket.Connected)
                {
                    cleanup.Add(client);
                    continue;
                }

                if (client.socket.Available > 0)
                {
                    int br = client.socket.Receive(client.buffer, SocketStateObject.BufferSize, SocketFlags.Partial);
                    client.sb.Append(Encoding.UTF8.GetString(client.buffer, 0, br));
                    string tmp = client.sb.ToString();
                    if (tmp.Contains("\n"))
                    {
                        string[] pcs = tmp.Replace("\r", "").Split('\n');
                        foreach (string line in pcs.Take(pcs.Length - 1))
                        {
                            try
                            {
                                LuaRuntime.Run(line, luaEnv);
                            }
                            catch (Exception e)
                            {
                                A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
                                luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
                            }
                        }
                        client.sb = new StringBuilder(pcs.Last());
                    }
                }

                if (sendData.Length > 0)
                {
                    client.socket.Send(sendData);
                }
            }

            connections.RemoveAll(i => cleanup.Contains(i));
        }
Ejemplo n.º 2
0
 void FixedUpdate()
 {
     if (fixedUpdateCodes != "")
     {
         t.SetNameValue("deltaTime", new LuaNumber(Time.fixedDeltaTime));
         LuaRuntime.Run(fixedUpdateCodes, t);
     }
 }
Ejemplo n.º 3
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Console.WriteLine("Initializing GUI...");
     LuaRuntime.Run(System.IO.File.ReadAllText("Core.lua"));
     Application.Run(new Form1());
     Console.WriteLine("Exiting...");
 }
Ejemplo n.º 4
0
 void Start()
 {
     t = LuaRuntime.CreateGlobalEnviroment();
     t.SetNameValue("selfVehicle", new LuaUserdata(self, true));
     t.SetNameValue("sceneManager", new LuaUserdata(SceneManager.instance, true));
     if (initCodes != "")
     {
         LuaRuntime.Run(initCodes, t);
     }
 }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            LasmParser p    = new LasmParser();
            LuaFile    file = p.Parse(@"
        .const ""print""
        .const ""Hello""
        getglobal 0 0
        loadk 1 1
        call 0 2 1
        return 0 1
        ");

            file.StripDebugInfo();
            string code = file.Compile();

            try
            {
                LuaFile f = Disassembler.Disassemble(code);
                System.IO.FileStream fs = new System.IO.FileStream("lasm.luac", System.IO.FileMode.Create);
                //foreach (char c in code)
                foreach (char c in f.Compile())
                {
                    fs.WriteByte((byte)c);
                }
                fs.Close();

                // Test chunk compiling/loading
                string s    = f.Main.Compile(f);
                Chunk  chnk = Disassembler.DisassembleChunk(s);

                // Test execution of code
                string s2 = f.Compile();
                LuaRuntime.Run(s2);
                LuaRuntime.Run(code);
                Console.WriteLine("The above line should say 'Hello'. If it doesn't there is an error.");
                Console.WriteLine(LASMDecompiler.Decompile(file));
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            try
            {
                LuaFile lf = p.Parse("breakpoint 0 0 0");
                LuaRuntime.Run(lf.Compile());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Test(s) done. Press any key to continue.");
            Console.ReadKey(true);
        }
Ejemplo n.º 6
0
        public static void Main(string[] cmd_args_1938475092347027340582734) // random name doesnt interfere with my variables
        {
            // Create a global environment
            LuaTable t = LuaRuntime.CreateGlobalEnviroment();

            // to add an item, dont use AddValue, it sticks it into the back
            // instead, use SetNameValue
            t.SetNameValue("obj", new LuaString("sample object"));

            // we can set the MetaTable of item "obj", but first we must get it from
            // the global environment:
            LuaValue val = t.GetValue("obj");

            // We can then print "val"
            Console.WriteLine(val.ToString());   // --> sample object

            // to register methods, use the Register function (using Addresses or delegates)
            t.Register("samplefunc", delegate(LuaValue[] args)
            {
                return(new LuaNumber(100));
            });

            // To run Lua, use the Run function in LuaRuntime
            // we pass "t" as the specified environment, otherwise it will
            // create a new environment to run in.
            LuaRuntime.Run("print(\"obj:\", obj, \"\nsamplefunc:\", samplefunc())", t);

            // we can also call .NET methods using Lua-created .NET object
            // such as:
            LuaRuntime.Run("obj2 = script.create(\"CSharpExampleProject.TestClass\")", t);
            LuaRuntime.Run("print(\"testint:\", obj2.testint, \"TestFunc:\", obj2.TestFunc())", t);

            // the reason for this is because script.create returns an advanced Userdata with
            // metatables that check any indexing or setting and map them to the .NET object
            // if it doesn't find it, it throws an error
            //LuaRuntime.Run("obj2.ThisValueDoesntExistInDotNet = \"hey\"", t);
            // the same value was printed twice, with different functions each time, proving its not actually there:
            //Console.WriteLine(LuaRuntime.Run("return \"Sample attemption at creating an object: \" .. tostring(obj2.ThisValueDoesntExistInDotNet)", t));
            // Console.WriteLine was used to show that you can print the returned value of executed code
            //LuaRuntime.Run("print(obj2.ThisValueDoesntExistInDotNet)", t);

            // Lua can also create "classes"
            LuaRuntime.Run("c = class()", t);
            Console.WriteLine(LuaRuntime.Run("return c", t));

            // You can also call functions defined in #Lua
            LuaFunction f = LuaRuntime.Run("return function() print\"a function says hai\" end", t) as LuaFunction;

            f.Invoke(new LuaValue[] { });

            // Let you see the output
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Ejemplo n.º 7
0
        public static void Main(string[] cmd_args_1938475092347027340582734) // random name doesn't interfere with my variables
        {
            // Create a global environment
            LuaInterface i = LuaRuntime.GetLua();

            // to add an item, simply use the LuaInterface like a table
            i["obj"] = "sample object";

            // we can set the MetaTable of item "obj", but first we must get it from
            // the global environment:
            var val = i["obj"];

            // We can then print "val"
            Console.WriteLine(val.ToString());   // --> sample object

            // to register methods, use the Register function (using Addresses or delegates)
            i.RegisterFunction("samplefunc", null, (new Func <object>(delegate()
            {
                return(100);
            })).Method);

            // To run Lua, use the Run function in LuaRuntime
            // we pass "t" as the specified environment, otherwise it will
            // create a new environment to run in.
            LuaRuntime.Run(@"print(""obj:"", obj, ""\nsamplefunc:"", samplefunc())");

            // we can also call .NET methods using Lua-created .NET object
            // such as:
            LuaRuntime.Run("obj2 = clr.create(\"CSharpExampleProject.TestClass\")");
            // Notice the ':' in the method invocation (call)...
            LuaRuntime.Run("print(\"testint:\", obj2.testint, \"TestFunc:\", obj2:TestFunc())");

            // the reason for this is because clr.create returns an advanced Userdata with
            // metatables that wrap the .net object
            //LuaRuntime.Run("obj2.ThisValueDoesntExistInDotNet = \"hey\"", t);
            // the same value was printed twice, with different functions each time, proving its not actually there:
            //Console.WriteLine(LuaRuntime.Run("return \"Sample attemption at creating an object: \" .. tostring(obj2.ThisValueDoesntExistInDotNet)", t));
            // Console.WriteLine was used to show that you can print the returned value of executed code
            //LuaRuntime.Run("print(obj2.ThisValueDoesntExistInDotNet)", t);

            // You can also call functions defined in #Lua
            LuaFunction f = LuaRuntime.Run("return function() print\"a function says hai\" end")[0] as LuaFunction;

            f.Call();

            // Another class example
            i["t2"] = new Test2();
            LuaRuntime.Run("t2.Values:Sort() print(t2[1])");

            // Let you see the output
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
 public void runScript(string script)
 {
     try
     {
         LuaRuntime.GlobalEnvironment = luaEnv;
         LuaRuntime.Run(script, luaEnv);
     }
     catch (Exception e)
     {
         A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
         luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
     }
 }
Ejemplo n.º 9
0
 private void parseScript(GenericRoll bet)
 {
     try
     {
         bool Win = bet.data.status.Equals("WIN");
         SetLuaVars();
         Lua["win"]           = Win;
         Lua["currentprofit"] = bet.data.profit;
         Lua["lastBet"]       = bet;
         LuaRuntime.SetLua(Lua);
         LuaRuntime.Run("dobet()");
         GetLuaVars();
     }
     catch
     {
     }
 }
 public void consoleRun()
 {
     A8Console.WriteLine("> " + line);
     if (history.LastOrDefault() != line)
     {
         history.Add(line);
     }
     historyPos = 0;
     try
     {
         LuaRuntime.GlobalEnvironment = luaEnv;
         LuaRuntime.Run(line, luaEnv);
     }
     catch (Exception e)
     {
         A8Console.WriteLine(e.GetType().Name + ": " + e.Message);
         luaEnv.SetNameValue("lastError", ObjectToLua.ToLuaValue(e));
     }
     line = "";
 }
Ejemplo n.º 11
0
        public static LuaValue LoadString(LuaValue[] values)
        {
            LuaString code = values[0] as LuaString;

            return(LuaRuntime.Run(code.Text, LuaRuntime.GlobalEnvironment));
        }
Ejemplo n.º 12
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);
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
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();
                            }
                        }
Ejemplo n.º 14
0
        void ConsoleIn(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                SetLuaVars();
                LCindex = 0;
                LastCommands.Add(txtConsoleIn.Text);
                if (LastCommands.Count > 26)
                {
                    LastCommands.RemoveAt(0);
                }
                txtConsole.Text += (txtConsoleIn.Text) + "\r\n";
                if (txtConsoleIn.Text.ToLower() == "start()")
                {
                    LuaRuntime.SetLua(Lua);
                    try
                    {
                        LuaRuntime.Run(txtScript.Text);
                        Start();
                    }
                    catch (Exception ex)
                    {
                        txtConsole.Text += ("LUA ERROR!!") + "\r\n";
                        txtConsole.Text += (ex.Message) + "\r\n";
                    }
                }

                else
                {
                    try
                    {
                        LuaRuntime.SetLua(Lua);
                        LuaRuntime.Run(txtConsoleIn.Text);
                    }
                    catch (Exception ex)
                    {
                        txtConsole.Text += ("LUA ERROR!!") + "\r\n";
                        txtConsole.Text += (ex.Message) + "\r\n";
                    }
                }

                txtConsoleIn.Text = "";
                GetLuaVars();
            }
            if (e.Key == Key.Up)
            {
                if (LCindex < LastCommands.Count)
                {
                    LCindex++;
                }
                if (LastCommands.Count > 0)
                {
                    txtConsoleIn.Text = LastCommands[LastCommands.Count - LCindex];
                }
            }
            if (e.Key == Key.Down)
            {
                if (LCindex > 0)
                {
                    LCindex--;
                }
                if (LCindex <= 0)
                {
                    txtConsoleIn.Text = "";
                }
                else if (LastCommands.Count > 0)
                {
                    txtConsoleIn.Text = LastCommands[LastCommands.Count - LCindex];
                }
            }
        }
Ejemplo n.º 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                if (t.ThreadState == System.Threading.ThreadState.Running)
                {
                    return;
                }
            }
            try
            {
                //if (o.Length == 2)
                {
                    t = new Thread(new ThreadStart(delegate
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        try
                        {
                            //string tmp = "return string.dump(loadstring([==============================[" + textBox1.Text + "]==============================]))";
                            string tmp = "return Load([==============================[" + textBox1.Text + "]==============================])";
                            sw.Stop();
                            object[] o       = LuaRuntime.Run(tmp);
                            LuaFunction func = o[0] as LuaFunction;
                            LuaFile f        = o[1] as LuaFile;
                            Invoke(new Action(delegate
                            {
                                textBox2.Text = "";
                                textBox2.Clear();
                                textBox3.Text = "";
                                dump(f.Main);
                            }));
                            SharpLua.Lua.OnOpcodeRun += Lua_OnOpcodeRun;
                            sw.Start();
                            //func.Call();

                            func.Call();
                            SharpLua.Lua.OnOpcodeRun -= Lua_OnOpcodeRun;
                            //func.Call();
                        }
                        catch (System.Exception ex)
                        {
                            Invoke(new Action(delegate { textBox2.Text = ex.ToString(); }));
                        }
                        finally
                        {
                            Invoke(new Action(delegate
                            {
                                sw.Stop();
                                label1.Text = "Ran in less than " + sw.ElapsedMilliseconds + " ms";
                            }));
                        }
                    }));
                    t.Start();
                }
            }
            catch (System.Exception ex)
            {
                textBox2.Text = ex.ToString();
            }
            finally
            {
            }
        }