コード例 #1
0
ファイル: GuiMethods.cs プロジェクト: Skippeh/Pokemon-RPG
 public void Register(Lua lua)
 {
     lua.RegisterFunction("game.getWidth", this, this.GetType().GetMethod("GetWindowWidth"));
     lua.RegisterFunction("game.getHeight", this, this.GetType().GetMethod("GetWindowHeight"));
     lua.RegisterFunction("game.getCenter", this, this.GetType().GetMethod("GetWindowCenter"));
     lua.RegisterFunction("gui.registerMenu", this, this.GetType().GetMethod("RegisterMenu"));
 }
コード例 #2
0
ファイル: Program_Lua.cs プロジェクト: TheScience/SMProxy
        private static Lua ConfigureLua(PacketReader PacketReader, StreamWriter outputWriter)
        {
            Lua LuaInterpreter = new Lua();

            LuaInterpreter.RegisterFunction("readByte", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadByte" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readShort", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadShort" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readInt", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadInt" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readLong", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadLong" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readString", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadString" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readSlot", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadSlot" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readMob", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadMobMetadata" && m.GetParameters().Length == 0
                ).First());
            LuaInterpreter.RegisterFunction("readBytes", PacketReader, typeof(PacketReader).GetMethod("ReadBytes"));
            LuaInterpreter.RegisterFunction("readBoolean", PacketReader, typeof(PacketReader).GetMethods().Where(
                    m => m.Name == "ReadBoolean" && m.GetParameters().Length == 0
                ).First());

            return LuaInterpreter;
        }
コード例 #3
0
ファイル: Engine.cs プロジェクト: MatthewChrobakHistory/TCG
        public Engine()
        {
            Lua = new LuaInterface.Lua();
            Lua.NewTable("Client");
            Lua.RegisterFunction("Client.ChangeState", this, this.GetType().GetMethod("ChangeClientState"));
            Lua.NewTable("NS");
            Lua.NewTable("NS.Minor");

            Lua.RegisterFunction("NS.Run", this, this.GetType().GetMethod("MethodName"));
            Lua.RegisterFunction("Print", this, this.GetType().GetMethod("Print"));
            Lua.RegisterFunction("print", this, this.GetType().GetMethod("Print"));
        }
コード例 #4
0
 internal void SetupScope(Lua lua, Quest q)
 {
     foreach(ConstructorInfo constructor in registeredTriggers)
     {
         lua.RegisterFunction(constructor.DeclaringType.Name, q, constructor);
     }
 }
コード例 #5
0
ファイル: API.cs プロジェクト: resaka/HearthstoneBot
        public API()
        {
            Log.log("API constructed");

            try
            {
                lua = new Lua();

                Log.log("Setting script path...");
                string lua_script_path = Plugin.getBothPath() + "LuaScripts/";
                lua["script_path"] = lua_script_path;
                Log.log("Done");

                // Print to screen
                lua.RegisterFunction("__csharp_print_to_log", this, typeof(API).GetMethod("__csharp_print_to_log"));

                // Game functions
                // Query for cards
                lua.RegisterFunction("__csharp_cards", this, typeof(API).GetMethod("getCards"));
                lua.RegisterFunction("__csharp_card", this, typeof(API).GetMethod("getCard"));
                // Query the number of crystals
                lua.RegisterFunction("__csharp_crystals", this, typeof(API).GetMethod("getCrystals"));

                // Query about entities
                lua.RegisterFunction("__csharp_entity_bool", this, typeof(API).GetMethod("getEntityBool"));
                lua.RegisterFunction("__csharp_entity_value", this, typeof(API).GetMethod("getEntityValue"));

                // Utility functions
                lua.RegisterFunction("__csharp_convert_to_entity", this, typeof(API).GetMethod("__csharp_convert_to_entity"));

                // Function for creating actions (returned by turn_action function)
                lua.RegisterFunction("__csharp_play_card", this, typeof(API).GetMethod("PlayCard"));
                lua.RegisterFunction("__csharp_attack_enemy", this, typeof(API).GetMethod("AttackEnemy"));

                Log.log("Loading Main.lua...");
                lua.DoFile(lua_script_path + "Main.lua");
                Log.log("Done");
            }
            catch(LuaException e)
            {
                Log.error("EXCEPTION");
                Log.error(e.ToString());
                Log.error(e.Message);
            }
            catch(Exception e)
            {
                Log.error(e.ToString());
            }
            Log.log("Scripts loaded constructed");
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: qq353571619/VsStudyLuan
        static void Main(string[] args)
        {
            LuaInterface.Lua lua = new LuaInterface.Lua();
            lua.DoString("print('12345')");
            lua.DoFile("test.lua");
            Console.WriteLine((string)lua["str"]);//访问lua中的变量

            Program p = new Program();

            lua.RegisterFunction("NormalMethod", p, p.GetType().GetMethod("Method"));
            lua.DoString("NormalMethod()");
            lua.RegisterFunction("StaticMethod", null, typeof(Program).GetMethod("StaticMethod"));
            lua.DoString("StaticMethod()");

            lua.DoFile("go.lua");

            Console.ReadKey();
        }
コード例 #7
0
ファイル: Lua.cs プロジェクト: welterde/obsidian
 internal bool Start(string initfile)
 {
     lua = new LuaInterface.Lua();
     lua["server"] = server;
     lua.RegisterFunction("Is",this,this.GetType().GetMethod("Is"));
     if (!File.Exists(initfile)) {
         server.Log("Initfile '"+initfile+"' not found.");
         return false;
     } try { lua.DoFile(initfile); }
     catch (Exception e) { Error(e); return false; }
     return true;
 }
コード例 #8
0
 internal bool Start(string initfile)
 {
     lua           = new LuaInterface.Lua();
     lua["server"] = server;
     lua.RegisterFunction("Is", this, this.GetType().GetMethod("Is"));
     if (!File.Exists(initfile))
     {
         server.Log("Initfile '" + initfile + "' not found.");
         return(false);
     }
     try { lua.DoFile(initfile); }
     catch (Exception e) { Error(e); return(false); }
     return(true);
 }
コード例 #9
0
ファイル: GameMethods.cs プロジェクト: Skippeh/Pokemon-RPG
 public void Register(Lua lua)
 {
     lua.RegisterFunction("game.exit", this, this.GetType().GetMethod("Exit"));
     lua.RegisterFunction("game.setState", this, this.GetType().GetMethod("SetState"));
     lua.RegisterFunction("game.addState", this, this.GetType().GetMethod("AddState"));
     lua.RegisterFunction("game.getXnaGame", this, this.GetType().GetMethod("GetXnaGame"));
     lua.RegisterFunction("game.getGraphicsDevice", this, this.GetType().GetMethod("GetGraphicsDevice"));
     lua.RegisterFunction("game.startGame", this, GetType().GetMethod("StartGame"));
 }
コード例 #10
0
ファイル: AFGWin.cs プロジェクト: tsinfeng/EnjoyTest
        private void RunLua(object obj)
        {
            try
            {
                string luaFile = obj as string;
                Lua luaVM = new Lua();

                luaVM.RegisterFunction("FMSignal", this, this.GetType().GetMethod("FMSignal"));
                luaVM.RegisterFunction("Single", this, this.GetType().GetMethod("Single"));
                luaVM.RegisterFunction("Output", this, this.GetType().GetMethod("Output"));
                luaVM.RegisterFunction("OutputLine", this, this.GetType().GetMethod("OutputLine"));
                luaVM.RegisterFunction("Sleep", this, this.GetType().GetMethod("Sleep"));
                luaVM.RegisterFunction("SetAcVolt", this, this.GetType().GetMethod("SetAcVolt"));
                luaVM.RegisterFunction("SetDcVolt", this, this.GetType().GetMethod("SetDcVolt"));
                luaVM.RegisterFunction("SetAcCurrent", this, this.GetType().GetMethod("SetAcCurrent"));
                luaVM.RegisterFunction("SetDcCurrent", this, this.GetType().GetMethod("SetDcCurrent"));
                luaVM.RegisterFunction("MeterValue", this, this.GetType().GetMethod("MeterValue"));

                luaVM.DoFile(luaFile);


                luaVM.Close();
            }
            catch (Exception)
            {

            }
            finally
            {
                /*
                this.Invoke(new MethodInvoker(delegate
                {

                     this.buttonLuaRun.Text = "运行脚本";
                }));
                 * */
                if (this.IsHandleCreated)
                {
                    MethodInvoker meth = new MethodInvoker(delegate
                    {
                        this.buttonLuaRun.Text = "运行脚本";
                    });

                    this.BeginInvoke(meth);
                }

            }

        }
コード例 #11
0
        public static void Initialise(string script_name)
        {
            try
            {
                Console.WriteLine("Initializing lua...");

                _manager = new Lua();
                _functions = new LuaFunctions();

                try
                {
                    _manager.RegisterFunction("PrintToConsole", _functions, _functions.GetType().GetMethod("PrintToConsole"));
                    _manager.RegisterFunction("PrintToChat", _functions, _functions.GetType().GetMethod("PrintToChat"));
                }
                catch
                {
                    Console.WriteLine("Oof. Registering functions shouldnt have failed.");
                }

                try
                {
                    _manager.DoFile(script_name);
                }
                catch
                {
                    Console.WriteLine("Error opening the script.");
                }
                _initialised = true;
                _filename = script_name;
            }
            catch
            {
                Console.WriteLine("Error initialising lua");
                _initialised = false;
            }
        }
コード例 #12
0
ファイル: LuaHelper.cs プロジェクト: henke37/BizHawk
		public static LuaTable ToLuaTable(Lua lua, object obj)
		{
			var table = lua.NewTable();

			var type = obj.GetType();

			var methods = type.GetMethods();
			foreach (var method in methods)
			{
				if (method.IsPublic)
				{
					table[method.Name] = lua.RegisterFunction("", obj, method);
				}
			}

			return table;
		}
コード例 #13
0
 public static void Initialize()
 {
     lua = new Lua();
     Instance = new luaInstance();
     // lua.RegisterFunction(Lua_String, Instance, Instange.GetType().GetMethod(Method_String));
     lua.RegisterFunction("Vect3", Instance, Instance.GetType().GetMethod("Vect3"));
     lua.RegisterFunction("Quater", Instance, Instance.GetType().GetMethod("Quater"));
     lua.RegisterFunction("SpawnInterceptor", Instance, Instance.GetType().GetMethod("SpawnInterceptor"));
     lua.RegisterFunction("SpawnAssaultFighter", Instance, Instance.GetType().GetMethod("SpawnAssaultFighter"));
     lua.RegisterFunction("SpawnBomber", Instance, Instance.GetType().GetMethod("SpawnBomber"));
     lua.RegisterFunction("SpawnCapitalShip", Instance, Instance.GetType().GetMethod("SpawnCapitalShip"));
 }
コード例 #14
0
        /// <summary>
        /// Registers all public instance methods in an object tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
        /// </summary>
        /// <param name="lua">The Lua VM to add the methods to</param>
        /// <param name="o">The object to get the methods from</param>
        public static void TaggedInstanceMethods(Lua lua, object o)
        {
            if (lua == null)
            {
                throw new ArgumentNullException("lua");
            }
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            foreach (MethodInfo method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
            {
                foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true))
                {
                    Debug.Assert(attribute.Name != "");
                    lua.RegisterFunction(attribute.Name ?? method.Name, o, method);
                }
            }
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: James226/WildstarUT
        private static void Main(string[] args)
        {
            using (Lua = new Lua())
            {
                Lua["_TESTRUNNER"] = true;
                Lua.DoFile("Apollo.lua");
                Lua.DoString("function Print(string) print(string) end");
                Lua.RegisterFunction("XmlDoc.CreateFromFile", null, typeof(XmlDoc).GetMethod("CreateFromFile"));

                string addonDir = "TrackMaster";
                string addonPath = FindTocFile(args.FirstOrDefault()) ?? Path.Combine(Environment.GetEnvironmentVariable("appdata"), @"NCSOFT\Wildstar\Addons\" + addonDir + @"\");
                Directory.SetCurrentDirectory(addonPath);

                Lua.DoString(string.Format("package.path = package.path .. ';{0}/?.lua'", addonPath.Replace('\\', '/')));
                XDocument toc = XDocument.Load(Path.Combine(addonPath, "toc.xml"));
                Lua.DoString(string.Format("Apollo.__AddonName = '{0}'", toc.Element("Addon").Attribute("Name").Value));
                foreach (XElement script in toc.Element("Addon").Elements("Script"))
                {
                    Console.WriteLine("Loading File: " + script.Attribute("Name").Value);
                    Lua.DoFile(Path.Combine(addonPath, script.Attribute("Name").Value));
                }

                //foreach (var testFiles in Directory.GetFiles(Path.Combine(addonPath, "Tests")))
                //{
                //    Console.WriteLine("Loading File: " + testFiles);
                //    Lua.DoFile(testFiles);
                //}
                try
                {
                    //Lua.DoString("Apollo.GetPackage('WildstarUT-1.0').tPackage:RunAllTests()");

                    Lua.DoString("Apollo.GetPackage('Lib:Busted-2.0').tPackage:RunAllTests()");
                }
                catch (LuaException ex)
                {
                    Console.WriteLine("Execution Error: " + ex);
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions
        /// </summary>
        /// <param name="lua">The Lua VM to add the methods to</param>
        /// <param name="type">The class type to get the methods from</param>
        public static void TaggedStaticMethods(Lua lua, Type type)
        {
            if (lua == null)
            {
                throw new ArgumentNullException("lua");
            }
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (!type.IsClass)
            {
                throw new ArgumentException("The type must be a class!", "type");
            }

            foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
            {
                foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false))
                {
                    Debug.Assert(attribute.Name != "");
                    lua.RegisterFunction(attribute.Name ?? method.Name, null, method);
                }
            }
        }
コード例 #17
0
ファイル: BaseMethods.cs プロジェクト: Skippeh/Pokemon-RPG
 public void Register(Lua lua)
 {
     lua.RegisterFunction("write", this, this.GetType().GetMethod("Write"));
     lua.RegisterFunction("writeLine", this, this.GetType().GetMethod("WriteLine"));
 }
コード例 #18
0
ファイル: GameMain.cs プロジェクト: parappayo/Bushido-Burrito
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            RenderMan = new RenderMan(this);  // provides rendering utils

            GameWorld = new GameWorld(this);  // holds game state
            InputMan = new InputMan(this, GameWorld);  // handles user input
            // process input events before updating game state
            Components.Add(InputMan);
            Components.Add(GameWorld);

            mHexTileMap = new HexTileMap(this, GameWorld.MapData);
            mUnitDrawer = new UnitDrawer(this, GameWorld.UnitData);

            mUserCursor = new UserCursor(this);
            mUserCursor.DrawUserCursor = DrawUserCursor;
            mUserCursor.PushBoundaryEvent += new EventHandler(mUserCursor_PushBoundaryEvent);
            mUserCursor.GamePadEnabled = true;
            mUserCursor.KeyboardEnabled = true;

            // order in which components are added determines draw order
            Components.Add(mHexTileMap);
            Components.Add(mUnitDrawer);
            Components.Add(mUserCursor);

            #if !XBOX
            // process Lua scripts
            LuaEngine = new Lua();
            LuaEngine.RegisterFunction("MapData", GameWorld.MapData, GameWorld.MapData.GetType().GetMethod("AddData"));
            LuaEngine.DoFile("scripts/main.lua");
            #endif

            base.Initialize();
        }
コード例 #19
0
ファイル: LuaTool.cs プロジェクト: puggsoy/tiledggd-pe-
        internal void loadFile(String filename)
        {
            if (string.IsNullOrEmpty(luaFile))
                throw new Exception("No Lua file specified");

            if (!System.IO.File.Exists(filename))
                throw new Exception("Cannot find file " + filename);

            // store the file data
            this.theData = System.IO.File.ReadAllBytes(filename);

            interp = new Lua();
            this.usedSetData = false;

            #region register predefined functions & variables
            // register the functions
            interp.RegisterFunction("read", this, this.GetType().GetMethod("read"));
            interp.RegisterFunction("read2", this, this.GetType().GetMethod("read2"));
            interp.RegisterFunction("readWORD", this, this.GetType().GetMethod("readWORD"));
            interp.RegisterFunction("readlWORD", this, this.GetType().GetMethod("readlWORD"));
            interp.RegisterFunction("readDWORD", this, this.GetType().GetMethod("readDWORD"));
            interp.RegisterFunction("readlDWORD", this, this.GetType().GetMethod("readlDWORD"));
            interp.RegisterFunction("readString", this, this.GetType().GetMethod("readString"));
            interp.RegisterFunction("readString2", this, this.GetType().GetMethod("readString2"));
            interp.RegisterFunction("stringToInt", this, this.GetType().GetMethod("stringToInt"));
            interp.RegisterFunction("setData", this, this.GetType().GetMethod("setData"));
            interp.RegisterFunction("setData2", this, this.GetType().GetMethod("setData2"));
            interp.RegisterFunction("addData", this, this.GetType().GetMethod("addData"));
            interp.RegisterFunction("addData2", this, this.GetType().GetMethod("addData2"));
            interp.RegisterFunction("toHexadecimal", this, this.GetType().GetMethod("ToHexadecimal"));

            // register the default variables
            interp["filesize"] = theData.Length;
            interp["filename"] = filename.Substring(filename.LastIndexOfAny(new char[] { '\\', '/' }) + 1);
            interp["filepath"] = filename.Substring(0, filename.LastIndexOfAny(new char[] { '\\', '/' }) + 1);
            #endregion

            // read the plugin
            try
            {
                interp.DoFile(this.luaFile);

                // if the variable invalid has been set, display it, and reset the data
                if (interp["invalid"] != null)
                {
                    MainWindow.ShowError(interp.GetString("invalid"));
                    this.bData.Data = new byte[0];
                }
                else
                {
                    #region format
                    // try to read the format
                    if (interp["format"] != null)
                    {
                        int format = (int)(double)interp["format"];
                        switch (this.Parent.BindingType)
                        {
                            case BindingType.GRAPHICS:
                                if (format < 1 || format > 7)
                                    MainWindow.ShowError("Plugin warning: the format of the graphics should range from 1 up to and including 7.\n"
                                                              + "Value " + format + " is ignored");
                                else
                                    GraphicsData.GraphFormat = (GraphicsFormat)format;
                                break;
                            case BindingType.PALETTE:
                                if (format < 5 || format > 7)
                                    MainWindow.ShowError("Plugin warning: the format of the palette should range from 5 up to and including 7.\n"
                                                              + "Value " + format + " is ignored");
                                else
                                    PaletteData.PalFormat = (PaletteFormat)format;
                                break;
                        }
                    }
                    #endregion

                    if (this.parentBinding.BindingType == BindingType.PALETTE || (int)GraphicsData.GraphFormat >= 5)
                    {
                        #region palette order
                        if (interp["order"] != null)
                        {
                            string s = ((string)interp["order"]).ToUpper();
                            if (s.Length != 3 || !s.Contains("R") || !s.Contains("G") || !s.Contains("B"))
                                MainWindow.ShowError("Plugin warning: the colour order is invalid.\n"
                                                     + "Value " + s + " is ignored.");
                            else
                                PaletteData.PalOrder = (PaletteOrder)Enum.Parse(typeof(PaletteOrder), s);
                        }
                        #endregion

                        #region alpha location
                        if (interp["alphaAtStart"] != null)
                        {
                            bool atStart = (bool)interp["alphaAtStart"];
                            PaletteData.AlphaSettings.Location = atStart ? AlphaLocation.START : AlphaLocation.END;
                        }
                        #endregion

                        #region ignore alpha
                        if (interp["ignoreAlpha"] != null)
                        {
                            bool ignore = (bool)interp["ignoreAlpha"];
                            PaletteData.AlphaSettings.IgnoreAlpha = ignore;
                        }
                        #endregion

                        #region enable stretch
                        if (interp["enableAlphaStrech"] != null)
                        {
                            bool enable = (bool)interp["enableAlphaStrech"];
                            PaletteData.AlphaSettings.Stretch = enable;
                        }
                        #endregion

                        #region stretch settings
                        if (interp["alphaStretch"] != null)
                        {
                            LuaTable t = interp.GetTable("alphaStretch");

                            if (t["min"] != null)
                                PaletteData.AlphaSettings.Minimum = (byte)(double)t["min"];
                            else if(t[0] != null)
                                PaletteData.AlphaSettings.Minimum = (byte)(double)t[0];

                            if (t["max"] != null)
                                PaletteData.AlphaSettings.Maximum = (byte)(double)t["max"];
                            else if (t[0] != null)
                                PaletteData.AlphaSettings.Maximum = (byte)(double)t[1];
                        }
                        #endregion
                    }

                    #region Endianness
                    if (interp["bigendian"] != null)
                    {
                        bool isBE = (bool)interp["bigendian"];
                        switch (this.Parent.BindingType)
                        {
                            case BindingType.GRAPHICS:
                                GraphicsData.IsBigEndian = isBE; break;
                            case BindingType.PALETTE:
                                PaletteData.IsBigEndian = isBE; break;
                        }
                    }
                    #endregion

                    #region tile size
                    if (interp["tilesize"] != null)
                    {
                        System.Drawing.Point size, oldSize;
                        switch(this.parentBinding.BindingType)
                        {
                            case BindingType.GRAPHICS: size = oldSize = GraphicsData.TileSize; break;
                            case BindingType.PALETTE: size = oldSize = PaletteData.TileSize; break;
                            default: throw new Exception(string.Format("Unknown BindingType {0:s}", this.parentBinding.BindingType.ToString()));
                        }
                        try
                        {
                            LuaTable t = interp.GetTable("tilesize");

                            if (t["x"] != null)
                                size.X = (int)(double)t["x"];
                            else if (t[0] != null)
                                size.X = (int)(double)t[0];

                            if (t["y"] != null)
                                size.Y = (int)(double)t["y"];
                            else if (t[1] != null)
                                size.Y = (int)(double)t[1];

                            switch (this.parentBinding.BindingType)
                            {
                                case BindingType.GRAPHICS: GraphicsData.TileSize = size; break;
                                case BindingType.PALETTE: PaletteData.TileSize = size; break;
                            }
                        }
                        catch (Exception)
                        {
                            MainWindow.ShowError("Plugin warning: invalid tile size provided.\nValue is ignored.");
                            switch (this.parentBinding.BindingType)
                            {
                                case BindingType.GRAPHICS: GraphicsData.TileSize = oldSize; break;
                                case BindingType.PALETTE: PaletteData.TileSize = oldSize; break;
                            }
                        }
                    }
                    #endregion

                    #region tiled
                    if (interp["tiled"] != null)
                    {
                        bool tl;
                        switch (this.parentBinding.BindingType)
                        {
                            case BindingType.GRAPHICS:
                                tl = GraphicsData.Tiled;
                                try { GraphicsData.Tiled = (bool)interp["tiled"]; }
                                catch (Exception)
                                {
                                    MainWindow.ShowError("Plugin warning: invalid tile size provided.\nValue is ignored.");
                                    GraphicsData.Tiled = tl;
                                }
                                break;
                            case BindingType.PALETTE:
                                tl = PaletteData.Tiled;
                                try { PaletteData.Tiled = (bool)interp["tiled"]; }
                                catch (Exception)
                                {
                                    MainWindow.ShowError("Plugin warning: invalid tile size provided.\nValue is ignored.");
                                    PaletteData.Tiled = tl;
                                }
                                break;
                            default: throw new Exception(string.Format("Unknown BindingType {0:s}", this.parentBinding.BindingType.ToString()));
                        }
                    }
                    #endregion

                    if (this.Parent.BindingType == BindingType.GRAPHICS)
                    {
                        #region width
                        if (interp["width"] != null)
                        {
                            uint origW = GraphicsData.Width;
                            try
                            {
                                uint w = (uint)(double)interp["width"];
                                GraphicsData.Width = w;
                            }
                            catch (Exception)
                            {
                                GraphicsData.Width = origW;
                                MainWindow.ShowError("Plugin warning: invalid width.\n"
                                                     + "Value " + interp.GetString("width") + " is ignored.");
                            }
                        }
                        #endregion

                        #region height
                        if (interp["height"] != null)
                        {
                            uint origH = GraphicsData.Height;
                            try
                            {
                                uint h = (uint)(double)interp["height"];
                                GraphicsData.Height = h;
                            }
                            catch (Exception)
                            {
                                GraphicsData.Height = origH;
                                MainWindow.ShowError("Plugin warning: invalid height.\n"
                                                     + "Value " + interp.GetString("height") + " is ignored.");
                            }
                        }
                        #endregion
                    }

                    if (!usedSetData)
                        this.bData.Data = this.theData;

                    if (interp["warning"] != null)
                        MainWindow.ShowWarning(interp.GetString("warning"));
                }
            }
            catch (Exception e)
            {
                MainWindow.ShowError("Plugin error: \n" + e.Message);
            }

            // close and delete the interpreter, and delete the data
            interp.Close();
            interp = null;
            this.theData = null;
        }
コード例 #20
0
ファイル: SkillForm.cs プロジェクト: viticm/pap2
 private void InitLua()
 {
     try
     {
         m_lua = new Lua();
         m_lua["MainForm"] = (MainForm)ParentForm;
         m_lua["SkillForm"] = this;
         //m_lua["oo"] = new tcls1();
         //建立环境帮助函数
         m_lua.DoString("function trace() \r\n end\r\n");
         string sCode = "____main_env_varTable = {}\r\nlocal function _MakeEnv(envname)\r\n	____main_env_varTable[envname] = {}\r\n	_G[\"__fname__\"..envname] = ____main_env_varTable[envname]\r\n____main_env_varTable[envname].envname = envname\r\n	setmetatable(____main_env_varTable[envname], {__index = _G})\r\nend\r\nfunction _ChgEnv(envname)\r\n	if (envname == nil) then\r\n        setfenv(2, _G)\r\n	elseif (____main_env_varTable[envname] == nil) then\r\n  		_MakeEnv(envname)\r\n  		setfenv(2, ____main_env_varTable[envname])\r\n else\r\n    	setfenv(2, ____main_env_varTable[envname])\r\n	end\r\nend\r\n";
         m_lua.DoString(sCode);
         m_lua.RegisterFunction("ClearTreeNodes", this, typeof(SkillForm).GetMethod("ClearTreeNodes"));
         m_lua.RegisterFunction("AddTreeNodes", this, typeof(SkillForm).GetMethod("AddTreeNodes"));
         m_lua.RegisterFunction("SqlQueryOnce", this, typeof(SkillForm).GetMethod("SqlQueryOnce"));
         m_lua.RegisterFunction("SqlInsertLevelRecord", this, typeof(SkillForm).GetMethod("SqlInsertLevelRecord"));
         m_lua.RegisterFunction("SqlSetPrimKey", this, typeof(SkillForm).GetMethod("SqlSetPrimKey"));
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
コード例 #21
0
        static void Main(string[] args)
        {
            Lua lua = new Lua();
            lua["x"] = 3;
            lua.DoString("y=x");
            Console.WriteLine("y={0}", lua["y"]);

            {
                object[] retVals = lua.DoString("return 1,'hello'");
                Console.WriteLine("{0},{1}", retVals[0], retVals[1]);
            }

            {
                KopiLua.Lua.lua_pushcfunction(lua.luaState, Func);
                KopiLua.Lua.lua_setglobal(lua.luaState, "func");
                Console.WriteLine("registered 'func'");

                double result = (double)lua.DoString("return func(1,2,3)")[0];
                Console.WriteLine("{0}", result);
            }

            {
                Bar bar = new Bar();
                bar.x = 2;
                lua["bar"] = bar;
                Console.WriteLine("'bar' registered");

                object o = lua["bar"];
                Console.WriteLine("'bar' read back as {0}", o);
                Console.WriteLine(o == bar ? "same" : "different");
                Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]);

                double result = (double)lua.DoString("return bar.x")[0];
                Console.WriteLine("lua says bar.x = {0}", result);

                lua.DoString("bar.x = 4");
                Console.WriteLine("now bar.x = {0}", bar.x);
            }

            {
                Foo foo = new Foo();
                lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply"));
                Console.WriteLine("registered 'multiply'");

                double result = (double)lua.DoString("return multiply(3)")[0];
                Console.WriteLine("{0}", result);
            }

            Console.ReadLine();
        }
コード例 #22
0
ファイル: LuaFunctions.cs プロジェクト: Spectrewiz/TShockMMO
        public static void setupFunctions()
        {
            Lua lua = new Lua();
            Functions functions = new Functions();

            lua.RegisterFunction("Broadcast", functions, functions.GetType().GetMethod("Broadcast"));//string message
            lua.RegisterFunction("Achievement", functions, functions.GetType().GetMethod("AddAchievement"));//int id, string playername, bool broadcast
            lua.RegisterFunction("AchievementByName", functions, functions.GetType().GetMethod("AddAchievementByName"));//string achievementname, string playername, bool broadcast
            lua.RegisterFunction("AddXP", functions, functions.GetType().GetMethod("AddXP"));//int amount, string playername
            lua.RegisterFunction("SetXP", functions, functions.GetType().GetMethod("SetXP"));//int amount, string playername
            lua.RegisterFunction("Wait", functions, functions.GetType().GetMethod("Wait"));//int time
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
            lua.RegisterFunction("", functions, functions.GetType().GetMethod(""));
        }
コード例 #23
0
ファイル: Client.cs プロジェクト: GavinKenna/Muroidea
        /// <summary>
        /// This method takes care of all of the LUA init. It assigns all of the functions that will be used.
        /// </summary>
        private void InitLUA()
        {
            lua = new Lua();

            lua.RegisterFunction("Hello", this, this.GetType().GetMethod("SayHello"));
            lua.RegisterFunction("AddTwoNumbers", this, this.GetType().GetMethod("AddTwoNumbers"));
            lua.RegisterFunction("GetIP", this, this.GetType().GetMethod("GetIP"));
            lua.RegisterFunction("Quit", this, this.GetType().GetMethod("Quit"));
            lua.RegisterFunction("RetrieveFile", this, this.GetType().GetMethod("RetrieveFile"));
            lua.RegisterFunction("MessageComputer", this, this.GetType().GetMethod("MessageComputer"));
            lua.RegisterFunction("GetComputerName", this, this.GetType().GetMethod("GetComputerName"));
            lua.RegisterFunction("GetCompID", this, this.GetType().GetMethod("GetCompID"));
            lua.RegisterFunction("GetCPUDetails", this, this.GetType().GetMethod("GetCPUDetails"));
            lua.RegisterFunction("GetMoboDetails", this, this.GetType().GetMethod("GetMoboDetails"));
            lua.RegisterFunction("GetRAMDetails", this, this.GetType().GetMethod("GetRAMDetails"));
            lua.RegisterFunction("GetStorageDetails", this, this.GetType().GetMethod("GetStorageDetails"));
            lua.RegisterFunction("GetVideoDetails", this, this.GetType().GetMethod("GetVideoDetails"));
            lua.RegisterFunction("GetAllInfo", this, this.GetType().GetMethod("GetAllInfo"));
            lua.RegisterFunction("GetMACAddress", this, this.GetType().GetMethod("GetMACAddress"));
            lua.RegisterFunction("InitFTPDirectory", this, this.GetType().GetMethod("InitFTPDirectory"));
            lua.RegisterFunction("GetFTPDirectory", this, this.GetType().GetMethod("GetFTPDirectory"));

            lua.RegisterFunction("GetComputerDetails", this, this.GetType().GetMethod("GetComputerDetails")); //GetComputerDetails
            lua.RegisterFunction("GetHardwareDetails", this, this.GetType().GetMethod("GetHardwareDetails")); //GetHardwareDetails
            lua.RegisterFunction("SendHardwareDetails", this, this.GetType().GetMethod("SendHardwareDetails")); //GetHardwareDetails
            lua.RegisterFunction("SendComputerDetails", this, this.GetType().GetMethod("SendComputerDetails")); //GetHardwareDetails
            lua.RegisterFunction("SendHardwareUsage", this, this.GetType().GetMethod("SendHardwareUsage")); //GetHardwareDetails

            lua.RegisterFunction("RemoteAcceptFTP", this, this.GetType().GetMethod("RemoteAcceptFTP"));
            lua.RegisterFunction("RemoteSendFTP", this, this.GetType().GetMethod("RemoteSendFTP"));

            //Process Commands
            lua.RegisterFunction("GetProcessDetails", this, this.GetType().GetMethod("GetProcessDetails"));
            lua.RegisterFunction("StartProcess", this, this.GetType().GetMethod("StartProcess"));
            lua.RegisterFunction("RestartProcesses", this, this.GetType().GetMethod("RestartProcesses"));
            lua.RegisterFunction("StopProcesses", this, this.GetType().GetMethod("StopProcesses"));

            //Service Commands
            lua.RegisterFunction("GetServiceDetails", this, this.GetType().GetMethod("GetServiceDetails"));
            lua.RegisterFunction("StartService", this, this.GetType().GetMethod("StartService"));
            lua.RegisterFunction("RestartServices", this, this.GetType().GetMethod("RestartServices"));
            lua.RegisterFunction("StopServices", this, this.GetType().GetMethod("StopServices"));
            lua.RegisterFunction("EnableServices", this, this.GetType().GetMethod("EnableServices"));
            lua.RegisterFunction("DisableServices", this, this.GetType().GetMethod("DisableServices"));
            lua.RegisterFunction("AutoServices", this, this.GetType().GetMethod("AutoServices"));

            //Scheduled Task Commands
            lua.RegisterFunction("AddTask", this, this.GetType().GetMethod("AddTask"));
            lua.RegisterFunction("AddAdvanceTask", this, this.GetType().GetMethod("AddAdvanceTask"));
            lua.RegisterFunction("GetTaskDetails", this, this.GetType().GetMethod("GetTaskDetails"));
            lua.RegisterFunction("AddDailyTrigger", this, this.GetType().GetMethod("AddDailyTrigger"));
            lua.RegisterFunction("AddWeeklyTrigger", this, this.GetType().GetMethod("AddWeeklyTrigger"));
            lua.RegisterFunction("AddMonthlyTrigger", this, this.GetType().GetMethod("AddMonthlyTrigger"));
            lua.RegisterFunction("AddStartupTrigger", this, this.GetType().GetMethod("AddStartupTrigger"));
            lua.RegisterFunction("AddAction", this, this.GetType().GetMethod("AddAction"));
            lua.RegisterFunction("AddActionAdvanced", this, this.GetType().GetMethod("AddActionAdvanced"));
            lua.RegisterFunction("DeleteTrigger", this, this.GetType().GetMethod("DeleteTrigger"));
            lua.RegisterFunction("DeleteAction", this, this.GetType().GetMethod("DeleteAction"));
            lua.RegisterFunction("DeleteTask", this, this.GetType().GetMethod("DeleteTask"));

            //System Operations
            lua.RegisterFunction("PowerControl", this, this.GetType().GetMethod("PowerControl"));
            lua.RegisterFunction("GetUptime", this, this.GetType().GetMethod("GetUptime"));
            lua.RegisterFunction("GetUptimeHours", this, this.GetType().GetMethod("GetUptimeHours"));

            //GetTemps()

            //Database Stuff
            lua.RegisterFunction("GetCompDB", this, this.GetType().GetMethod("GetCompDB"));
            lua.RegisterFunction("GetSystemDB", this, this.GetType().GetMethod("GetSystemDB"));

            lua.RegisterFunction("RemoteAcceptFTPFromClient", this, this.GetType().GetMethod("RemoteAcceptFTPFromClient"));
            //SendFTPToClient
            lua.RegisterFunction("SendFTPToClient", this, this.GetType().GetMethod("SendFTPToClient"));
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: niuniuzhu/kopiluainterface
        static void Main(string[] args)
        {
            var lua = new Lua();

            Console.WriteLine("LuaTable disposal stress test...");
            {
                lua.DoString("a={b={c=0}}");
                for (var i = 0; i < 100000; ++i)
                {
                    // Note that we don't even need the object type to be LuaTable - c is an int.
                    // Simply indexing through tables in the string expression was enough to cause
                    // the bug...
                    var z = lua["a.b.c"];
                }
            }
            Console.WriteLine("    ... passed");

            Console.WriteLine("LuaFunction disposal stress test...");
            {
                lua.DoString("function func() return func end");
                for (var i = 0; i < 100000; ++i)
                {
                    var f = lua["func"];
                }
            }
            Console.WriteLine("    ... passed");

            lua["x"] = 3;
            lua.DoString("y=x");
            Console.WriteLine("y={0}", lua["y"]);

            {
                lua.DoString("luanet.load_assembly('SimpleTest')");
                lua.DoString("Foo = luanet.import_type('SimpleTest.Foo')");
                lua.DoString("method = luanet.get_method_bysig(Foo, 'OutMethod', 'SimpleTest.Foo', 'out SimpleTest.Bar')");
                Console.WriteLine(lua["method"]);
            }

            {
                object[] retVals = lua.DoString("return 1,'hello'");
                Console.WriteLine("{0},{1}", retVals[0], retVals[1]);
            }

            {
                KopiLua.Lua.lua_pushcfunction(lua.luaState, Func);
                KopiLua.Lua.lua_setglobal(lua.luaState, "func");
                Console.WriteLine("registered 'func'");

                double result = (double)lua.DoString("return func(1,2,3)")[0];
                Console.WriteLine("{0}", result);
            }

            {
                Bar bar = new Bar();
                bar.x = 2;
                lua["bar"] = bar;
                Console.WriteLine("'bar' registered");

                object o = lua["bar"];
                Console.WriteLine("'bar' read back as {0}", o);
                Console.WriteLine(o == bar ? "same" : "different");
                Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]);

                double result = (double)lua.DoString("return bar.x")[0];
                Console.WriteLine("lua says bar.x = {0}", result);

                lua.DoString("bar.x = 4");
                Console.WriteLine("now bar.x = {0}", bar.x);
            }

            {
                Foo foo = new Foo();
                lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply"));
                Console.WriteLine("registered 'multiply'");

                double result = (double)lua.DoString("return multiply(3)")[0];
                Console.WriteLine("{0}", result);
            }

            Console.WriteLine("Finished, press Enter to quit");
            Console.ReadLine();
        }
コード例 #25
0
ファイル: GUI.cs プロジェクト: Joxe/TacticsRPG
 public void registerFunctions(Lua a_lua)
 {
     a_lua.RegisterFunction("addButtonToGUI", this, this.GetType().GetMethod("addButton"));
     a_lua.RegisterFunction("getStateAsString", this, this.GetType().GetMethod("getStateAsString"));
 }
コード例 #26
0
ファイル: ExportManager.cs プロジェクト: viticm/pap2
        /// <summary>
        /// 初始化数据
        /// </summary>
        private bool Init()
        {
            try
            {
                outputDebugString(string.Format("{0} —— 开始Init初始化...", DateTime.Now));
                outputDebugString(string.Format("{0} —— 正在初始化sql连接...", DateTime.Now));

                // 初始化sql连接
                string fileName = Path.Combine(Application.StartupPath, "AutoExport.ini");
                string content = FileFolderHelper.FileToString(fileName);

                IniStructure m_inis = new IniStructure();
                m_inis = IniStructure.ReadIniWithContent(content);
                string connectString = m_inis.GetValue("General", "ConnString");
                conn = new SqlConnection(connectString);

                // 读取根目录路径
                outputDebugString(string.Format("{0} —— 正在初始化外部设置...", DateTime.Now));
                rootPath = m_inis.GetValue("General", "RootDir");

                // 读取导出表列表            
                string[] autoTableArray = m_inis.GetKeys("AutoExport");
                autoTableList.AddRange(autoTableArray);

                string[] customTableArray = m_inis.GetKeys("CustomExport");
                customTableList.AddRange(customTableArray);

                outputDebugString(string.Format("{0} —— 正在更新资源文件...", DateTime.Now));

                // 读取资源文件列表
                string[] fileArray = m_inis.GetKeys("Resource");
                fileList.AddRange(fileArray);

                // 读取自动导出表的配置信息
                string sqlString = string.Format("SELECT * FROM sys_export_table_cfg");
                configTable = GetDataTable(sqlString);

                // 更新资源文件
                if (Program.GSTEP != 2)
                    DownLoadResource();

                outputDebugString(string.Format("{0} —— 正在设置path...", DateTime.Now));

                // path更新
                EV ev = new EV();
                ev.evPath(Path.GetDirectoryName(Application.ExecutablePath));

                outputDebugString(string.Format("{0} —— 正在初始化lua虚拟机...", DateTime.Now));

                // 初始化lua虚拟机
                exportLua = new Lua();
                exportLua["Conn"] = conn;
                exportLua["RootDir"] = rootPath;
                string luaFile = Path.Combine(Application.StartupPath, "export.lua");
                exportLua.DoFile(luaFile);

                postExportLua = new Lua();
                postExportLua["___GIsServer"] = true;
                postExportLua["RootDir"] = rootPath;
                postExportLua["Conn"] = conn;
                postExportLua.RegisterFunction("GetDataTableRow", this, typeof(ExportManager).GetMethod("GetDataTableRow"));

                luaFile = Path.Combine(Application.StartupPath, "post_export.lua");
                postExportLua.DoFile(luaFile);


                outputDebugString(string.Format("{0} —— 完成所有初始化工作!", DateTime.Now));

                return true;

            }
            catch (Exception ex)
            {
                outputDebugStringError(string.Format("{0} —— 初始化init产生异常:{1}", DateTime.Now, ex.Message));
                return false;
            }            
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: Evangileon/FinData
 public TestCollection()
 {
     L = new Lua();
     L.RegisterFunction("FirstFunction", this, this.GetType().GetMethod("FirstFunction"));
     L.DoFile(".\\test.lua");
 }
コード例 #28
0
ファイル: Program.cs プロジェクト: huxia/kopiluainterface
        static void Main(string[] args)
        {
            Lua lua = new Lua();
            lua["x"] = 3;
            lua.DoString("y=x");
            Console.WriteLine("y={0}", lua["y"]);

            {
                lua.DoString("luanet.load_assembly('SimpleTest')");
                lua.DoString("Foo = luanet.import_type('SimpleTest.Foo')");
                lua.DoString("method = luanet.get_method_bysig(Foo, 'OutMethod', 'SimpleTest.Foo', 'out SimpleTest.Bar')");
                Console.WriteLine(lua["method"]);
            }

            {
                object[] retVals = lua.DoString("return 1,'hello'");
                Console.WriteLine("{0},{1}", retVals[0], retVals[1]);
            }

            {
                KopiLua.Lua.lua_pushcfunction(lua.luaState, Func);
                KopiLua.Lua.lua_setglobal(lua.luaState, "func");
                Console.WriteLine("registered 'func'");

                double result = (double)lua.DoString("return func(1,2,3)")[0];
                Console.WriteLine("{0}", result);
            }

            {
                Bar bar = new Bar();
                bar.x = 2;
                lua["bar"] = bar;
                Console.WriteLine("'bar' registered");

                object o = lua["bar"];
                Console.WriteLine("'bar' read back as {0}", o);
                Console.WriteLine(o == bar ? "same" : "different");
                Console.WriteLine("LuaInterface says bar.x = {0}", lua["bar.x"]);

                double result = (double)lua.DoString("return bar.x")[0];
                Console.WriteLine("lua says bar.x = {0}", result);

                lua.DoString("bar.x = 4");
                Console.WriteLine("now bar.x = {0}", bar.x);
            }

            {
                Foo foo = new Foo();
                lua.RegisterFunction("multiply", foo, foo.GetType().GetMethod("multiply"));
                Console.WriteLine("registered 'multiply'");

                double result = (double)lua.DoString("return multiply(3)")[0];
                Console.WriteLine("{0}", result);
            }

            Console.WriteLine("Finished, press Enter to quit");
            Console.ReadLine();
        }
コード例 #29
0
ファイル: DataBaseManager.cs プロジェクト: viticm/pap2
 private void InitLua()
 {
     m_lua = new Lua();
     m_lua.RegisterFunction("GetDataTableRow", this, typeof(DataBaseManager).GetMethod("GetDataTableRow"));
 }
コード例 #30
0
ファイル: Form1.cs プロジェクト: tsinfeng/TestTool
        private void RunLua(object obj)
        {
            try
            {
                string luaFile = obj as string;
                Lua luaVM = new Lua();

                luaVM.RegisterFunction("FMSignal", this, this.GetType().GetMethod("FMSignal"));
                luaVM.RegisterFunction("Single", this, this.GetType().GetMethod("Single"));
                luaVM.RegisterFunction("Output", this, this.GetType().GetMethod("Output"));
                luaVM.RegisterFunction("OutputLine", this, this.GetType().GetMethod("OutputLine"));
                luaVM.RegisterFunction("Sleep", this, this.GetType().GetMethod("Sleep"));

                luaVM.DoFile(luaFile);

                luaVM.Close();
            }
            catch (Exception)
            {

            }
            finally
            {
                this.Invoke(new MethodInvoker(delegate
                {

                    this.lua_button.Text = "运行脚本";
                }));
            }
        }
コード例 #31
0
ファイル: IoMethods.cs プロジェクト: Skippeh/Pokemon-RPG
 public void Register(Lua lua)
 {
     lua.RegisterFunction("io.loadFont", this, this.GetType().GetMethod("LoadFont"));
     lua.RegisterFunction("io.loadTexture", this, this.GetType().GetMethod("LoadTexture"));
 }
コード例 #32
0
ファイル: TestLua.cs プロジェクト: bobbyzhu/MonoLuaInterface
        /*
         * Sample test script that shows some of the capabilities of
         * LuaInterface
         */
        public static void Main()
        {
            Console.WriteLine("Starting interpreter...");
            Lua l=new Lua();

            Console.WriteLine("Reading test.lua file...");
            l.DoFile("test.lua");
            double width=l.GetNumber("width");
            double height=l.GetNumber("height");
            string message=l.GetString("message");
            double color_r=l.GetNumber("color.r");
            double color_g=l.GetNumber("color.g");
            double color_b=l.GetNumber("color.b");
            Console.WriteLine("Printing values of global variables width, height and message...");
            Console.WriteLine("width: "+width);
            Console.WriteLine("height: "+height);
            Console.WriteLine("message: "+message);
            Console.WriteLine("Printing values of the 'color' table's fields...");
            Console.WriteLine("color.r: "+color_r);
            Console.WriteLine("color.g: "+color_g);
            Console.WriteLine("color.b: "+color_b);
            width=150;
            Console.WriteLine("Changing width's value and calling Lua function print to show it...");
            l["width"]=width;
            l.GetFunction("print").Call(width);
            message="LuaNet Interface Test";
            Console.WriteLine("Changing message's value and calling Lua function print to show it...");
            l["message"]=message;
            l.GetFunction("print").Call(message);
            color_r=30;
            color_g=10;
            color_b=200;
            Console.WriteLine("Changing color's fields' values and calling Lua function print to show it...");
            l["color.r"]=color_r;
            l["color.g"]=color_g;
            l["color.b"]=color_b;
            l.DoString("print(color.r,color.g,color.b)");
            Console.WriteLine("Printing values of the tree table's fields...");
            double leaf1=l.GetNumber("tree.branch1.leaf1");
            string leaf2=l.GetString("tree.branch1.leaf2");
            string leaf3=l.GetString("tree.leaf3");
            Console.WriteLine("leaf1: "+leaf1);
            Console.WriteLine("leaf2: "+leaf2);
            Console.WriteLine("leaf3: "+leaf3);
            leaf1=30; leaf2="new leaf2";
            Console.WriteLine("Changing tree's fields' values and calling Lua function print to show it...");
            l["tree.branch1.leaf1"]=leaf1; l["tree.branch1.leaf2"]=leaf2;
            l.DoString("print(tree.branch1.leaf1,tree.branch1.leaf2)");
            Console.WriteLine("Returning values from Lua with 'return'...");
            object[] vals=l.DoString("return 2,3");
            Console.WriteLine("Returned: "+vals[0]+" and "+vals[1]);
            Console.WriteLine("Calling a Lua function that returns multiple values...");
            object[] vals1=l.GetFunction("func").Call(2,3);
            Console.WriteLine("Returned: "+vals1[0]+" and "+vals1[1]);
            Console.WriteLine("Creating a table and filling it from C#...");
            l.NewTable("tab");
            l.NewTable("tab.tab");
            l["tab.a"]="a!";
            l["tab.b"]=5.5;
            l["tab.tab.c"]=6.5;
            l.DoString("print(tab.a,tab.b,tab.tab.c)");
            Console.WriteLine("Setting a table as another table's field...");
            l["tab.a"]=l["tab.tab"];
            l.DoString("print(tab.a.c)");
            Console.WriteLine("Registering a C# static method and calling it from Lua...");

            // Pause so we can connect with the debugger
            // Thread.Sleep(30000);

            l.RegisterFunction("func1",null,typeof(TestLuaInterface).GetMethod("func"));
            vals1=l.GetFunction("func1").Call(2,3);
            Console.WriteLine("Returned: "+vals1[0]);
            TestLuaInterface obj=new TestLuaInterface();
            Console.WriteLine("Registering a C# instance method and calling it from Lua...");
            l.RegisterFunction("func2",obj,typeof(TestLuaInterface).GetMethod("funcInstance"));
            vals1=l.GetFunction("func2").Call(2,3);
            Console.WriteLine("Returned: "+vals1[0]);

            Console.WriteLine("Testing throwing an exception...");
            obj.ThrowUncaughtException();

            Console.WriteLine("Testing catching an exception...");
            obj.ThrowException();

            Console.WriteLine("Testing inheriting a method from Lua...");
            obj.LuaTableInheritedMethod();

            Console.WriteLine("Testing overriding a C# method with Lua...");
            obj.LuaTableOverridedMethod();

            Console.WriteLine("Stress test RegisterFunction (based on a reported bug)..");
            obj.RegisterFunctionStressTest();

            Console.WriteLine("Test structures...");
            obj.TestStructs();

            Console.WriteLine("Test Nullable types...");
            obj.TestNullable();

            Console.WriteLine("Test functions...");
            obj.TestFunctions();

            Console.WriteLine("Test event exceptions...");
            obj.TestEventException();
        }
コード例 #33
0
ファイル: QClasses.cs プロジェクト: Ijwu/TShock-Quest-System
        public void LoadQuest()
        {
            try
            {
                Lua lua = new Lua();
                QMain.TriggerHandler.SetupScope(lua, this);
                lua["Quest"] = this;
                lua["Player"] = this.player;
                lua["Color"] = new Color();

                lua.RegisterFunction("Add", this, this.GetType().GetMethod("Add"));
                lua.RegisterFunction("Prioritize", this, this.GetType().GetMethod("Prioritize"));
                lua.RegisterFunction("Enqueue", this, this.GetType().GetMethod("Enqueue"));
                lua.RegisterFunction("ClearQueue", this, this.GetType().GetMethod("ClearQueue"));

                lua.DoFile(this.path);
                this.player.TSPlayer.SendInfoMessage(string.Format("Quest {0} has started.", this.info.Name));

                if (triggers.Count == 0)
                    throw new LuaScriptException(string.Format("The script for the quest \"{0}\" never enqueues any triggers. Quests must enqueue at least one trigger.", this.info.Name), this.info.Path);

                running = true;

                currentTrigger = triggers.Last.Value;
                currentTrigger.Initialize();
                triggers.RemoveLast();
            }
            catch (Exception e)
            {
                System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();
                errorMessage.AppendLine(string.Format("Error in quest system while loading quest: Player: {0} QuestName: {1}", this.player.TSPlayer.Name, this.path));
                errorMessage.AppendLine(e.Message);
                errorMessage.AppendLine(e.StackTrace);
                TShockAPI.Log.ConsoleError(errorMessage.ToString());
            }
        }
コード例 #34
0
ファイル: LuaHelper.cs プロジェクト: GodLesZ/svn-dump
        /// <summary>
        /// Wraps an object to prepare it for passing to LuaInterface. If no name is specified, a 
        /// random one with the default length is used.
        /// </summary>
        public static object WrapObject(object toWrap, Lua state, string name = null)
        {
            if (toWrap is MulticastDelegate)
            {
                //We have to deal with a problem here: RegisterFunction does not really create
                //a new function, but a userdata with a __call metamethod. This works fine in all
                //except two cases: When Lua looks for an __index or __newindex metafunction and finds
                //a table or userdata, Lua tries to redirect the read/write operation to that table/userdata.
                //In case of our function that is in reality a userdata this fails. So we have to check
                //for these function and create a very thin wrapper arround this to make Lua see a function instead
                //the real userdata. This is no problem for the other metamethods, these are called independent
                //from their type. (If they are not nil ;))
                MulticastDelegate function = (toWrap as MulticastDelegate);

                if (name != null && (name.EndsWith("__index") || name.EndsWith("__newindex")))
                {
                    string tmpName = LuaHelper.GetRandomString();
                    state.RegisterFunction(tmpName, function.Target, function.Method);
                    state.DoString(String.Format("function {0}(...) return {1}(...) end", name, tmpName), "DynamicLua internal operation");
                }
                else
                {
                    if (name == null)
                        name = LuaHelper.GetRandomString();
                    state.RegisterFunction(name, function.Target, function.Method);
                }
                return null;
            }
            else if (toWrap is DynamicLuaTable)
            {
                dynamic dlt = toWrap as DynamicLuaTable;
                return (LuaTable)dlt;
            }
            else
                return toWrap;
        }
コード例 #35
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hellow Lua");


            #region 使用C#写lua,并在lua虚拟机中执行 ---字段属性篇
            // 第一种 : 创建lua虚拟机的形式直接写lua
            Lua lua = new Lua(); // 创建lua虚拟机(lua解析器)
            lua["m_Age"]        = 23;
            lua["m_PlayerName"] = "胖儿子";
            lua.NewTable("m_HeroTable");
            Console.WriteLine(lua["m_Age"] + "----" + lua["m_PlayerName"]);

            // C#和lua中变量对应参考:
            // nil ------ null
            // string ------ System.String
            // number ------ System.Double
            // boolean ------ System.Boolean
            // table ------ LuaInterface.LuaTable
            // function ------ LuaInterface.LuaFunction

            double age  = (double)lua["m_Age"];
            string name = (string)lua["m_PlayerName"];
            Console.WriteLine(age + "---" + name);


            // 第二种 : 使用lua.DoString() 编写Lua
            lua.DoString("account = 20170504");
            lua.DoString("str = 'youga'");
            object[] result = lua.DoString("return str, account");
            foreach (object item in result)
            {
                Console.WriteLine(item);
            }


            // 第三种: lua.DoFile() 编写Lua

            //1. 解决方案 - 右击 LuaInterface(项目名) - 添加 - 新建项 - 建一个名为LuaTest.lua的类
            //2. 把lua代码放进去,把编码格式改为ANSI(可以用Notepad++)
            //3. 右击LuaTest.lua - 属性 - 复制到输出目录 - 选择始终复制即可
            lua.DoFile("LuaTest.lua");

            #endregion


            #region 使用C#写lua,并在lua虚拟机中执行 ---方法篇
            //1. 将一个类里面的普通方法注册进lua中并执行
            TestClass t = new TestClass();
            // 注意: 普通方法一定要注明是哪个对象
            lua.RegisterFunction("MyNormalCLRMethod", t, t.GetType().GetMethod("MyNormalCLRMethod"));
            lua.DoString("MyNormalCLRMethod()");
            // 如果是开发时一般名字要保持一致,这里只是为了演示C#代码给lua执行的意思

            //2. 将一个类里面的静态方法注册进Lua中并执行
            lua.RegisterFunction("MyStaticCLRMethod", null, typeof(TestClass).GetMethod("MyStaticCLRMethod"));
            lua.DoString("MyStaticCLRMethod()");

            #endregion
            Console.ReadKey();
            lua.Dispose();
        }
コード例 #36
0
ファイル: Preprocessor.cs プロジェクト: krikelin/LerosClient
 public Preprocessor()
 {
     Lua = new Lua();
     Lua.RegisterFunction("print", this, this.GetType().GetMethod("print"));
 }
コード例 #37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="path"></param>
 /// <param name="target"></param>
 /// <param name="function"></param>
 /// <returns></returns>
 public LuaFunction RegisterFunction(string path, object target, MethodBase function)
 {
     return(_lua.RegisterFunction(path, target, function));
 }