Пример #1
0
        static void Main(string[] args)
        {
            using (var lua = new Lua())
            {
                lua.DoFile("Apollo.lua");

                var luaUnit = @"C:/git/luaunit";
                var addonDir = "TrackMaster";
                var addonPath = Path.Combine(Environment.GetEnvironmentVariable("appdata"), @"NCSOFT\Wildstar\Addons\" + addonDir + @"\");

                lua.DoString(string.Format("package.path = package.path .. ';{0}/?.lua;{1}/?.lua'", luaUnit, addonPath.Replace('\\', '/')));
                var toc = XDocument.Load(Path.Combine(addonPath, "toc.xml"));
                foreach (var script in toc.Element("Addon").Elements("Script"))
                {
                    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("require('luaunit'):run()");
                }
                catch (LuaException ex)
                {
                    Console.WriteLine("Execution Error: " + ex.ToString());
                }
                //Console.ReadLine();
            }
        }
Пример #2
0
 public void Init(string strAPIInfoFile)
 {
     m_strCode = "";
     m_strAPIInfoFile = strAPIInfoFile;
     m_lua = new Lua();
     m_lua.DoFile(m_strAPIInfoFile);
     m_luatable = m_lua.GetTable("APIInfo");
     m_nClassCount = m_luatable.Keys.Count;
     m_strClass = new string[m_nClassCount];
     m_strClassInCode = new string[m_nClassCount];
     m_strIniFileName = Application.StartupPath + "\\Plugins\\LuaCheck\\API.temp.lua";
     m_lua1 = new Lua();
     m_lua1.DoFile(m_strIniFileName);
     int n = 0;
     foreach (string str in m_luatable.Keys)
     {
         m_strClass[n] = (string)(((LuaTable)m_luatable[str])["Name"]);
         n++;
     }
     
     //object ob;
     //foreach (ob in m_luatable)
     //{
     //    strClass[] = ((LuaTable)ob)["Name"];
     
     //}
     //object ob = m_luatable["1"];
     //object ob1 = ((LuaTable)ob)["Name"];
 }
Пример #3
0
        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();
        }
Пример #4
0
 /// <summary>
 /// 初始化数据
 /// </summary>
 private void Init()
 {
     string luaFile = Path.Combine(Application.StartupPath, "ConfigEdit.lua");
     FileInfo fi = new FileInfo(luaFile);
     if(fi.Exists)
     {
         lua = new Lua();
         lua.DoFile(luaFile);
     }
 }
Пример #5
0
        public GUIAddon(string a_filePath)
        {
            m_lua = new Lua();
            ((GameState)Game.getInstance().getCurrentState()).getGUI().registerFunctions(m_lua);
            m_lua.DoFile(a_filePath);

            m_onLoad = m_lua.GetFunction("OnLoad");
            m_onUpdate = m_lua.GetFunction("OnUpdate");
            m_onDraw = m_lua.GetFunction("OnDraw");
        }
Пример #6
0
        //[STAThread]
        private static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                // For attaching from the debugger
                // Thread.Sleep(20000);

                using (var lua = new LuaInterface.Lua())
                {
                    //lua.OpenLibs();			// steffenj: Lua 5.1.1 API change (all libs already opened in Lua constructor!)
                    lua.NewTable("arg");
                    LuaTable argc = (LuaTable)lua["arg"];
                    argc[-1] = "LuaRunner";
                    argc[0]  = args[0];

                    for (int i = 1; i < args.Length; i++)
                    {
                        argc[i] = args[i];
                    }

                    argc["n"] = args.Length - 1;

                    try
                    {
                        //Console.WriteLine("DoFile(" + args[0] + ");");
                        lua.DoFile(args[0]);
                    }
                    catch (Exception e)
                    {
                        // steffenj: BEGIN error message improved, output is now in decending order of importance (message, where, stacktrace)
                        // limit size of strack traceback message to roughly 1 console screen height
                        string trace = e.StackTrace;

                        if (e.StackTrace.Length > 1300)
                        {
                            trace = e.StackTrace.Substring(0, 1300) + " [...] (traceback cut short)";
                        }

                        Console.WriteLine();
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source + " raised a " + e.GetType().ToString());
                        Console.WriteLine(trace);

                        // wait for keypress if there is an error
                        Console.ReadKey();
                        // steffenj: END error message improved
                    }
                }
            }
            else
            {
                Console.WriteLine("LuaRunner -- runs Lua scripts with CLR access");
                Console.WriteLine("Usage: luarunner <script.lua> [{<arg>}]");
            }
        }
Пример #7
0
        public static bool Reload(string assets_root)
        {
            FLua = new Lua();

            string path = assets_root + "scripts/dt_all.lua";

            Directory.SetCurrentDirectory(assets_root + "../");

            FLua.DoFile(path);

            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
        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);
                }
            }
        }
Пример #10
0
        public static void Main(string[] args)
        {
            if(args.Length > 0)
            {
                // For attaching from the debugger
                // Thread.Sleep(20000);

                using(Lua lua = new Lua())
                {
                    //lua.OpenLibs();			// steffenj: Lua 5.1.1 API change (all libs already opened in Lua constructor!)
                    lua.NewTable("arg");
                    LuaTable argc = (LuaTable)lua["arg"];
                    argc[-1] = "LuaRunner";
                    argc[0] = args[0];

                    for(int i = 1; i < args.Length; i++)
                        argc[i] = args[i];

                    argc["n"] = args.Length - 1;

                    try
                    {
                        //Console.WriteLine("DoFile(" + args[0] + ");");
                        lua.DoFile(args[0]);
                    }
                    catch(Exception e)
                    {
                        // steffenj: BEGIN error message improved, output is now in decending order of importance (message, where, stacktrace)
                        // limit size of strack traceback message to roughly 1 console screen height
                        string trace = e.StackTrace;

                        if(e.StackTrace.Length > 1300)
                            trace = e.StackTrace.Substring(0, 1300) + " [...] (traceback cut short)";

                        Console.WriteLine();
                        Console.WriteLine(e.Message);
                        Console.WriteLine(e.Source + " raised a " + e.GetType().ToString());
                        Console.WriteLine(trace);

                        // wait for keypress if there is an error
                        Console.ReadKey();
                        // steffenj: END error message improved
                    }
                }
            }
            else
            {
                Console.WriteLine("LuaRunner -- runs Lua scripts with CLR access");
                Console.WriteLine("Usage: luarunner <script.lua> [{<arg>}]");
            }
        }
Пример #11
0
        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");
        }
Пример #12
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);
 }
Пример #13
0
        public ScriptNode(GameEntity gameEntity, string url)
        {
            mUrl = url;
            mScript = new Lua();

            AddFunctions(typeof(ScriptFunctions));
            AddFunctions(typeof(MilkHooks));

            mScript["gameObject"] = gameEntity;
            mScript["scene"] = Scene;
            attatchListeners(gameEntity);

            mScript.DoFile("Scripts//" + mUrl);
        }
Пример #14
0
        private void RunScript(string filename)
        {
            Stream file = SharedInformation.ContentManager.Load <Stream>(lua_folder + filename);
            string temp = Path.GetTempFileName();

            using (FileStream fs = new FileStream(temp, FileMode.Create))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    BinaryReader br    = new BinaryReader(file);
                    byte[]       bytes = br.ReadBytes((int)file.Length);

                    bw.Write(bytes);
                }
            }

            _luaparser.DoFile(temp);
            System.IO.File.Delete(temp);
        }
Пример #15
0
        /// <summary>
        /// Loads a world from a lua file
        /// </summary>
        /// <param name="filename">file to load the world from</param>
        /// <returns>true on success</returns>
        public bool load(string filename)
        {
            this.fname = filename;

            Lua lua = new Lua();
            var result = lua.DoFile(filename);
            foreach (DictionaryEntry member in lua.GetTable("world_data"))
            {
                if (member.Key.ToString() == "width")
                {
                    this.width = Convert.ToInt32(member.Value);
                }
                else if (member.Key.ToString() == "height")
                {
                    this.height = Convert.ToInt32(member.Value);
                }
                if (member.Key.ToString() == "paths")
                {
                    collision_segment = new ArrayList();
                    LuaTable paths = (LuaTable)member.Value;
                    foreach (DictionaryEntry path in paths)
                    {
                        ArrayList collision_path = new ArrayList();
                        LuaTable p = (LuaTable)path.Value;
                        foreach (DictionaryEntry point in p)
                        {
                            LuaTable point_data = (LuaTable)point.Value;
                            int x = Convert.ToInt32(point_data.Values.Cast<double>().ElementAt(0) * ppu);
                            int y = Convert.ToInt32(point_data.Values.Cast<double>().ElementAt(1) * ppu);
                            Console.WriteLine("X:" + x + ", Y:" + y);
                            collision_path.Add(new Point(x, y));
                        }
                        collision_segment.Add(collision_path);
                    }

                }
            }
            return true;
        }
Пример #16
0
        private bool IsBotTemplate(string file)
        {
            LuaInterface.Lua lua = new LuaInterface.Lua();

            try
            {

                lua.DoFile(file);

                LuaFunction on_event = lua.GetFunction("OnEvent");

                if(on_event == null)
                    return false;

                return true;
            }
            catch (Exception e)
            {
                AppContext.WriteLog(e.Message);
                return false;
            }
        }
        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;
            }
        }
Пример #18
0
 private void RunLuaCode(Lua engine, String location)
 {
     engine.DoFile(location);
 }
Пример #19
0
        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());
            }
        }
Пример #20
0
        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;
        }
Пример #21
0
 private string GetStringFromFile(string strTableName, string strFieldName, string strDefReturn)
 {
     Lua lua = new Lua();
     lua.DoFile(m_strIniFile);
     LuaTable tbl = lua.GetTable(strTableName);
     string strReturn = "";
     try
     {
         strReturn = (string)tbl[strFieldName];
     }
     catch (Exception e)
     {
         return strDefReturn;
     }
     return strReturn == null ? strDefReturn : strReturn;
 }
Пример #22
0
        /*
         * 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();
        }
Пример #23
0
        static void Main(string[] args)
        {
            Helper helper = Helper.GetHelper();
            helper.RecordLogText("开始准备合并AIType.tab文件");
            string fileName = Path.Combine(Application.StartupPath, @"config.ini");

            if (File.Exists(fileName))
            {
                string content = helper.GetFileContent(fileName);
                IniStructure iniStructure = IniStructure.ReadIniWithContent(content);

                string rootPath = iniStructure.GetValue("General", "RootDirectory");
                string parameterCountString = iniStructure.GetValue("General", "ParameterCount");
                int parameterCount = int.Parse(parameterCountString);

                // 需要导出一张旧的AIType表作为中间文件
                fileName = Path.Combine(rootPath, @"settings\AIType.tab");
                content = helper.GetFileContent(fileName);
                
                StringBuilder defaultLine = new StringBuilder();
                defaultLine.Append("0\t");

                for (int i = 0; i < parameterCount; i++)
                {
                    defaultLine.Append(string.Format("{0}\t", iniStructure.GetValue("DefaultValue", string.Format("ParameterValue{0}", i))));
                }

                defaultLine.Remove(defaultLine.Length - 1, 1);

                string newContent = CreateNewAITypeContent(content, defaultLine.ToString());
                helper.SaveData(fileName, newContent);

                string mapCountString = iniStructure.GetValue("General", "MapCount");
                int mapCount = int.Parse(mapCountString);                   
                List<string> mapList = new List<string>();

                for (int i = 0; i < mapCount; i++)
                {
                    string mapEnable = iniStructure.GetValue("MapList", string.Format("Enable{0}", i));

                    if (mapEnable == "1")
                    {
                        mapList.Add(iniStructure.GetValue("MapList", string.Format("MapName{0}", i)));
                    }
                }

                try
                {
                    Lua lua = new Lua(); // lua虚拟机
                    string luaFile = Path.Combine(Application.StartupPath, "exportScript.lua");
                    lua.DoFile(luaFile);

                    LuaFunction function = lua.GetFunction("ExportAIData");
                    string filePath = Path.Combine(rootPath, @"settings\NpcTemplate.tab");
                    function.Call(filePath, mapList);

                    helper.RecordLogText("AIType.tab合并完成");
                }
                catch (Exception ex)
                {
                    helper.RecordLogText("合并AIType文件时产生异常:" + ex.Message);
                }               

                fileName = Path.Combine(Application.StartupPath, "log.txt");
                helper.SaveData(fileName, helper.LogText);
            }
            else
            {
                helper.RecordLogText(string.Format("配置文件{0}不存在", fileName));
            }            
        }
Пример #24
0
        private void Export(string strMap)
        {
            string strPath = @"D:\Kingsoft\sword3-products\trunk\client\scripts\Map\" + strMap;
            Lua mLua = new Lua();
            mLua.DoFile(strPath + @"\include\对话.ls");

            string[] as_head = new string[]
            { 
                "COMMON_NPC_STRING",
                "COMMON_DOODAD_STRING",
                "COMMON_ITEM_STRING",
                "COMMON_TRAP_STRING",
                "COMMON_OTHER_STRING",

                "WANHUA_DOODAD_STRING",
                "WANHUA_ITEM_STRING",
                "WANHUA_COMMON_NPC_STRING"
            };           

            //遍历文件
            foreach(FileInfo fi in new DirectoryInfo(strPath).GetFiles("*.*", SearchOption.AllDirectories))
            {
                string strCode = Helper.FileToString(fi.FullName);
                if(fi.Name.ToLower().EndsWith(".lua"))
                {
                    //遍历表名
                    foreach(string strHead in as_head)
                    {
                        LuaTable lt_head = mLua.GetTable(strHead);
                        if (lt_head == null) continue;
                        //遍历某个表
                        foreach (string strKey in lt_head.Keys)
                        {
                            if (lt_head[strKey] is LuaTable)
                            {
                                string strPreDim = "";
                                LuaTable lt = lt_head[strKey] as LuaTable;
                                strPreDim = "LS_" + strKey + " = {";
                                foreach(object substring in lt.Values)
                                {
                                    strPreDim += "\r\n\t\"" + substring.ToString().Replace("\n", "\\n") + "\",";
                                }
                                if(strCode.IndexOf(strHead + "[\"" + strKey + "\"]") != -1)
                                    strCode = strPreDim.TrimEnd(new char[] { ',' }) + "\r\n}\r\n" + strCode;
                                strCode = strCode.Replace("math.random(", "Random(");
                                strCode = strCode.Replace(strHead + "[\"" + strKey + "\"]", "LS_" + strKey);                         
                            }
                            else if(lt_head[strKey] is string)
                            {
                                strCode = strCode.Replace(strHead + "[\"" + strKey + "\"]", "\"" + lt_head[strKey].ToString().Replace("\n", "\\n") + "\"");
                            }
                        }
                    }
                    strCode = strCode.Replace("Include(\"scripts/Map/" + strMap + "/include/对话.ls\");", "");
                }
                else if (fi.Name == "对话.ls")
                {
                    //donothing
                    continue;
                }
                else if (fi.Name.ToLower().EndsWith(".ls"))
                {
                    //对于用户自定义ls,不管了
                }
                else
                {
                    //SVN文件,不导
                    continue;
                }
                
                //转换后的东东存成文件
                string strOutPath = fi.FullName.Replace(strPath, @"D:\xxx\" + strMap);
                Helper.WriteStringToFile(strCode, strOutPath);
            }


        }
Пример #25
0
        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 = "运行脚本";
                }));
            }
        }
Пример #26
0
        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"));

                // Card functions
                lua.RegisterFunction("__csharp_get_our_battlefield_cards", this, typeof(API).GetMethod("__csharp_get_our_battlefield_cards"));
                lua.RegisterFunction("__csharp_get_enemy_battlefield_cards", this, typeof(API).GetMethod("__csharp_get_enemy_battlefield_cards"));
                lua.RegisterFunction("__csharp_get_hand_cards", this, typeof(API).GetMethod("__csharp_get_hand_cards"));
                lua.RegisterFunction("__csharp_drop_card", this, typeof(API).GetMethod("__csharp_drop_card"));
                lua.RegisterFunction("__csharp_enemy_hero_card", this, typeof(API).GetMethod("__csharp_enemy_hero_card"));
                lua.RegisterFunction("__csharp_is_card_tank", this, typeof(API).GetMethod("__csharp_is_card_tank"));

                // Query about card
                lua.RegisterFunction("__csharp_get_attack_of_entity", this, typeof(API).GetMethod("__csharp_get_attack_of_entity"));
                lua.RegisterFunction("__csharp_get_health_of_entity", this, typeof(API).GetMethod("__csharp_get_health_of_entity"));
                lua.RegisterFunction("__csharp_get_damage_of_entity", this, typeof(API).GetMethod("__csharp_get_damage_of_entity"));
                lua.RegisterFunction("__csharp_can_entity_attack", this, typeof(API).GetMethod("__csharp_can_entity_attack"));
                lua.RegisterFunction("__csharp_can_entity_be_attack", this, typeof(API).GetMethod("__csharp_can_entity_be_attack"));
                lua.RegisterFunction("__csharp_is_card_a_minion", this, typeof(API).GetMethod("__csharp_is_card_a_minion"));
                lua.RegisterFunction("__csharp_get_card_cost", this, typeof(API).GetMethod("__csharp_get_card_cost"));
                lua.RegisterFunction("__csharp_is_entity_exhausted", this, typeof(API).GetMethod("__csharp_is_entity_exhausted"));

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

                // Query about hero
                lua.RegisterFunction("__csharp_get_health_of_our_hero", this, typeof(API).GetMethod("__csharp_get_health_of_our_hero"));
                lua.RegisterFunction("__csharp_our_hero_crystals", this, typeof(API).GetMethod("__csharp_our_hero_crystals"));
                lua.RegisterFunction("__csharp_enemy_hero_crystals", this, typeof(API).GetMethod("__csharp_enemy_hero_crystals"));
                lua.RegisterFunction("__use_hero_power", this, typeof(API).GetMethod("__use_hero_power"));

                // Attack
                lua.RegisterFunction("__csharp_do_attack", this, typeof(API).GetMethod("__csharp_do_attack"));

                // End Turn
                lua.RegisterFunction("__csharp_end_turn", this, typeof(API).GetMethod("__csharp_end_turn"));

                Log.log("Loading Main.lua...");
                lua.DoFile(lua_script_path + "Main.lua");
                Log.log("Done");
            }
            catch(LuaException e)
            {
                Log.log("EXCEPTION");
                Log.log(e.ToString());
                Log.log(e.Message);
            }
            catch(Exception e)
            {
                Log.log(e.ToString());
            }
            Log.log("Scripts loaded constructed");
        }
Пример #27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns></returns>
 public object[] DoFile(string fileName)
 {
     return(_lua.DoFile(fileName));
 }
Пример #28
0
 public void Run()
 {
     Lua lua = new Lua();
     try
     {
         lua.DoFile(m_strExecFile);
     }
     catch (Exception Ex)
     {
         Console.WriteLine(Ex.Message);
         return;
     }
     LuaTable luaTable = lua.GetTable("EVENT_LIST");
     foreach (object Key in luaTable.Keys)
     {
         string strEventFunction = (string)luaTable[Key];
         //整理参数格式为   “param1, param2, param3, ”
         int nIndexP = strEventFunction.IndexOf("(") + 1;
         int nIndexE = strEventFunction.IndexOf(")");
         string strFunctionName = strEventFunction.Substring(0, nIndexP - 1);
         string strParam = strEventFunction.Substring(nIndexP, nIndexE - nIndexP) + ", ";
         nIndexP = 0;
         nIndexE = 0;
         strFunctionName = strFunctionName + "(";
         while (true)
         {
             nIndexP = nIndexE;
             nIndexE = strParam.IndexOf(", ", nIndexP) + 2;
             if (nIndexE == 1)
             {
                 break;
             }
             string strParamName = strParam.Substring(nIndexP, nIndexE - 2 - nIndexP);
             string sb = GetStringFromFile("GetParam", strParamName, "nil");
             if (sb == "nil")
             {
                 MessageBox.Show("配置文件中无法找到逻辑检查代入参数:" + strParamName);
             }
             strFunctionName = strFunctionName + sb + ", ";
         }
         if (strEventFunction.IndexOf("(") + 1 != strEventFunction.IndexOf(")"))
         {
             strFunctionName = strFunctionName.Substring(0, strFunctionName.Length - 2);
         }
         strFunctionName = strFunctionName + ")";
         try
         {
              lua.DoString(strFunctionName);
         }
         catch (Exception Ex)
         {   
             //过滤因为调用了不存在的Event引起的错误
             string strFunc = strFunctionName.Substring(0, strFunctionName.IndexOf("("));
             int nIndexEx = Ex.Message.IndexOf(strFunc);
             if (nIndexEx == -1)
             {
                 Console.WriteLine(Ex.Message);
             }
         }
     }
 }
Пример #29
0
        /// <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();
        }
Пример #30
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();
        }
Пример #31
0
        public void OnActivate()
        {
            // Create the lua state
            luastate = new Lua();

            // Setup hooks
            dctHooks = new Dictionary<string, List<LuaFunction>>();

            // Bind functions
            BindFunction("print", "print");

            luastate.NewTable("hook");
            BindFunction("hook.Add", "hook_Add");

            luastate.NewTable("library");
            BindFunction("library.AddWeapon", "library_AddWeapon");
            BindFunction("library.AddSystem", "library_AddSystem");
            BindFunction("library.AddRace", "library_AddRace");
            BindFunction("library.AddShipGenerator", "library_AddShipGenerator");
            BindFunction("library.AddSectorMapGenerator", "library_AddSectorMapGenerator");
            BindFunction("library.GetWeapon", "library_GetWeapon");
            BindFunction("library.GetSystem", "library_GetSystem");
            BindFunction("library.GetRace", "library_GetRace");
            BindFunction("library.GetShip", "library_GetShipGenerator");
            BindFunction("library.GetSectorMapGenerator", "library_GetSectorMapGenerator");
            BindFunction("library.CreateAnimation", "library_CreateAnimation");

            luastate.NewTable("ships");
            BindFunction("ships.NewDoor", "ships_NewDoor"); // Is there any way to call the constructor directly from lua code?

            // Load lua files
            if (!Directory.Exists("lua")) Directory.CreateDirectory("lua");
            foreach (string name in Directory.GetFiles("lua"))
                luastate.DoFile("lua/" + name);
        }
Пример #32
0
 public TestCollection()
 {
     L = new Lua();
     L.RegisterFunction("FirstFunction", this, this.GetType().GetMethod("FirstFunction"));
     L.DoFile(".\\test.lua");
 }
Пример #33
0
        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);
                }

            }

        }
Пример #34
0
        public void OnActivate()
        {
            // Create the lua state
            luastate = new Lua();

            // Setup hooks
            dctHooks = new Dictionary<string, List<LuaFunction>>();

            // Bind functions
            BindFunction("print", "print");

            luastate.NewTable("hook");
            BindFunction("hook.Add", "hook_Add");

            luastate.NewTable("library");
            BindFunction("library.AddWeapon", "library_AddWeapon");
            BindFunction("library.AddSystem", "library_AddSystem");
            BindFunction("library.AddRace", "library_AddRace");
            BindFunction("library.AddShipGenerator", "library_AddShipGenerator");
            BindFunction("library.AddSectorMapGenerator", "library_AddSectorMapGenerator");
            BindFunction("library.GetWeapon", "library_GetWeapon");
            BindFunction("library.GetSystem", "library_GetSystem");
            BindFunction("library.GetRace", "library_GetRace");
            BindFunction("library.GetShip", "library_GetShipGenerator");
            BindFunction("library.GetSectorMapGenerator", "library_GetSectorMapGenerator");
            BindFunction("library.CreateAnimation", "library_CreateAnimation");

            luastate.NewTable("ships");
            // You can't pass non-empty LuaTables to constructors. Possibly a bug in LI.
            BindFunction("ships.NewDoor", "ships_NewDoor");

            // Load lua files
            if (!Directory.Exists("lua")) Directory.CreateDirectory("lua");
            foreach (string name in Directory.GetFiles("lua"))
                luastate.DoFile(name);
        }
Пример #35
0
        /// <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;
            }            
        }
Пример #36
0
        /// <summary>
        /// 初始化逻辑管理器
        /// </summary>
        public void InitLogicManager()
        {
            string filePath = Path.Combine(Application.StartupPath, configFileName);
            
            if (File.Exists(filePath))
            {
                Lua lua = new Lua();

                lua.DoFile(filePath);
                LuaTable configTable = lua.GetTable("Config") as LuaTable;

                string[] diagramNameArray = new string[maxDiagramCount];

                foreach (object key in configTable.Keys)
                {
                    LuaTable logicManagerTable = configTable[key] as LuaTable;

                    if (logicManagerTable != null)
                    {
                        // 读取逻辑管理器信息
                        string logicManagerFilePath = logicManagerTable["LogicManagerFilePath"] as string;
                        string logicManagerClassName = logicManagerTable["LogicManagerClassName"] as string;
                        LogicBaseManager logicManager = null;

                        if (!string.IsNullOrEmpty(logicManagerFilePath) && !string.IsNullOrEmpty(logicManagerClassName))
                        {
                            logicManager = LoadLogicManager(logicManagerFilePath, logicManagerClassName);
                        }
                        else
                        {
                            logicManager = new LogicBaseManager();
                        }

                        // 读取显示名称
                        string logicManagerDisplayName = logicManagerTable["DisplayName"] as string;

                        if (!string.IsNullOrEmpty(logicManagerDisplayName))
                        {
                            logicManager.DisplayName = logicManagerDisplayName;
                        }                        

                        // 读取脚本生成插件信息
                        string compilerFilePath = logicManagerTable["CompilerFilePath"] as string;
                        string compilerClassName = logicManagerTable["CompilerClassName"] as string;

                        if (!string.IsNullOrEmpty(compilerFilePath) && !string.IsNullOrEmpty(compilerClassName))
                        {
                            logicManager.InitCompiler(compilerFilePath, compilerClassName);
                        }

                        // 检查是否是默认分类
                        int index = (int)(double)logicManagerTable["Index"];
                        diagramNameArray[index - 1] = logicManagerDisplayName;                        

                        // 读取数据元信息
                        LuaTable dataElementGroupTable = logicManagerTable["DataElement"] as LuaTable;

                        if (dataElementGroupTable != null)
                        {
                            foreach (object graphType in dataElementGroupTable.Keys)
                            {
                                LuaTable dataElementConfigTable = dataElementGroupTable[graphType] as LuaTable;

                                if (dataElementConfigTable != null)
                                {
                                    string dataElementFilePath = dataElementConfigTable["FilePath"] as string;
                                    string dataElementClassName = dataElementConfigTable["ClassName"] as string;

                                    logicManager.RegistDataElementInfo(graphType as string, dataElementFilePath, dataElementClassName);
                                }                                
                            }
                        }

                        logicManagerDictionary[logicManager.DisplayName] = logicManager;
                    }                    
                }

                foreach (string displayName in diagramNameArray)
                {
                    if (displayName != null)
                    {
                        diagramNameList.Add(displayName);
                    }
                }                
            }            
        }