Пример #1
0
 /// <summary>
 /// Run a Lua file.
 /// </summary>
 /// <param name="args"></param>
 private void RunFile(string file)
 {
     try
     {
         _scriptL = NewEnv();
         //TODO: Check for relative path and append script_path if it's available
         //HACK...
         Directory.SetCurrentDirectory((string)L["settings.script_path"]);
         System.IO.FileInfo f = new System.IO.FileInfo(file);
         if (f.Exists && f.Length > 0)
         {
             _scriptL["RUNNING__"] = true;
             _scriptL.DoFile(file);
             _scriptL.Close();
             _scriptL = null;
         }
         else
         {
             Log.WarnFormat("File Not Found: {0}\r\n", file);
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex.Message, ex);
         if (_logging)
         {
             Script("close");
         }
         _scriptL.Close();
         _scriptL = null;
     }
 }
Пример #2
0
 private void EndScript()
 {
     _scriptL["RUNNING__"] = false;
     System.Threading.Thread.Sleep(500);
     _scriptL.Close();
     _scriptL.Dispose();
     Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
 }
 public void Dispose()
 {
     if (_luaState != null)
     {
         _luaState.Close();
     }
 }
Пример #4
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 = "运行脚本";
                }));
            }
        }
Пример #5
0
 private bool minify_file(string inputFileName)
 {
     if (!File.Exists(inputFileName))
     {
         return(false);
     }
     try
     {
         Lua lua = new Lua();
         lua.DoFile("minify\\llex.lua");
         lua.DoFile("minify\\lparser.lua");
         lua.DoFile("minify\\optlex.lua");
         lua.DoFile("minify\\optparser.lua");
         lua.DoFile("minify\\squish.minify.lua");
         LuaFunction luaFunctionMinify = lua.GetFunction("minify_file");
         string      miniFileName      = Path.GetDirectoryName(inputFileName) + "\\" + Path.GetFileNameWithoutExtension(inputFileName) + ".mini" + Path.GetExtension(inputFileName);
         Console.WriteLine("write nimify file: " + miniFileName);
         luaFunctionMinify.Call(inputFileName, miniFileName);
         if (!File.Exists(miniFileName))
         {
             return(false);
         }
         lua.Close();
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
Пример #6
0
        public void CompileAndRunString()
        {
            state = new Lua();

            LuaStatus result = state.LoadString("x=1");

            stackDump(state);

            state.Call(0, 0);
            stackDump(state);

            result = state.LoadString("1");
            stackDump(state);

            state.PCall(0, 0, 0);
            stackDump(state);

            result = state.LoadString("print(x)"); // stdout??
            stackDump(state);

            state.Call(0, 0);
            stackDump(state);

            state.Close();
        }
Пример #7
0
        public void Init(object cbase)
        {
            if (pLuaVM != null)
            {
                pLuaVM.DebugHook -= new EventHandler <DebugHookEventArgs>(pLuaVM_DebugHook);
                pLuaVM.RemoveDebugHook();
                try
                {
                    pLuaVM.Close();
                }
                catch { }
                System.Threading.Thread.Sleep(1);

                if (AsyncThread != null)
                {
                    Terminate();
                }
            }

            baseClass    = cbase;
            baseType     = cbase.GetType();
            baseCallback = baseType.GetMethod("Callback");
            pLuaVM       = new Lua();
            pLuaFuncs    = new Hashtable();
            registerLuaFunctions(new LUAVMCommands());
            pLuaVM.SetDebugHook(EventMasks.LUA_MASKCOUNT, CommandsPerUpdate);
            pLuaVM.DebugHook += new EventHandler <DebugHookEventArgs>(pLuaVM_DebugHook);
        }
Пример #8
0
 public void Dispose()
 {
     if (lua != null)
     {
         lua.Close(); //no dispose(), this gives a access-violation...
         lua = null;
     }
 }
Пример #9
0
 public void Close()
 {
     RegisteredFunctions.Clear(_mainForm.Emulator);
     ScriptList.Clear();
     FormsLibrary.DestroyAll();
     _lua.Close();
     _lua = new Lua();
 }
Пример #10
0
 private void closeLua()
 {
     if (lua != null)
     {
         lua.Close();
         lua = null;
     }
 }
Пример #11
0
        public static void Quit()
        {
            _quit = true;

            if (State != null)
            {
                State.Close();
            }
        }
Пример #12
0
        private void LTWorking()
        {
            try
            {
                state_ = new Lua();
                LTInit(ref state_);
                while (state_ != null)
                {
                    LuaMsg msg;
                    if (ltqueue.TryDequeue(out msg))
                    {
                        switch (msg.type)
                        {
                        case LuaMsgType.Do:
                            Common.Trace("Do " + (string)msg.param[0]);
                            state_.DoString((string)msg.param[0]);
                            break;

                        case LuaMsgType.Start:
                            state_["Settings"]     = Common.settings;
                            state_["FightOptions"] = this.FightOptions;
                            state_.DoString("Set()");
                            while (IsFighting)
                            {
                                ifcolor.rebitmap();
                                state_.DoString("Fight()");
                                Thread.Sleep(FightOptions.interval);
                            }
                            break;

                        case LuaMsgType.Destory:
                            state_.Close();
                            state_.Dispose();
                            state_ = null;
                            return;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        Thread.Yield();
                    }
                }
            }
            catch (LuaScriptException e)
            {
                MessageBox.Show("LuaScriptException : " + e.Message + e.StackTrace, "脚本异常");
            }
            catch (LuaException e)
            {
                MessageBox.Show("LuaException :" + e.Message + e.StackTrace, "Lua异常");
            }
        }
Пример #13
0
        public void LuaScript_smoketest()
        {
            state = new Lua();
            LuaStatus result = state.LoadFile(GetScriptPath("smoketest"));

            Assert.AreEqual(LuaStatus.OK, result);

            result = state.PCall(0, -1, 0);
            Assert.AreEqual(LuaStatus.OK, result);

            state.Close();
        }
Пример #14
0
        public void TestUnref()
        {
            var state = new Lua();

            state.DoString("function f() end");
            LuaType type = state.GetGlobal("f");

            Assert.AreEqual(LuaType.Function, type, "#1");

            state.PushCopy(-1);
            state.Ref(LuaRegistry.Index);
            state.Close();
        }
Пример #15
0
        private void closeLua()
        {
            if (lua != null)
            {
                if (lua.IsExecuting)
                {
                    throw new InvalidOperationException("Lua is executing");
                }

                lua.Close();
                lua = null;
            }
        }
Пример #16
0
        private void btn1_Click(object sender, EventArgs e)
        {
            Texto1 = tBox1.Text;
            StreamWriter escrito = File.CreateText("C:\\Users\\DELL\\Documents\\Visual Studio 2012\\Projects\\WF1\\LuaEjemplo.txt");

            escrito.Write(Texto1.ToString());
            escrito.Close();

            Lua m_lua = new Lua();

            m_lua["tBox1"] = this.tBox1;
            m_lua.DoFile("C:\\Users\\DELL\\Documents\\Visual Studio 2012\\Projects\\WF1\\LuaEjemplo.txt");
            m_lua.Close();
        }
Пример #17
0
        public void Close()
        {
            foreach (var closeCallback in RegisteredFunctions
                     .Where(l => l.Event == "OnConsoleClose"))
            {
                closeCallback.Call();
            }

            RegisteredFunctions.Clear(_mainForm.Emulator);
            ScriptList.Clear();
            FormsLibrary.DestroyAll();
            _lua.Close();
            _lua = new Lua();
        }
Пример #18
0
        public void CompileResults()
        {
            state = new Lua();

            PrintChunk("", "Empty");

            PrintChunk("x=1");

            PrintChunk("1");

            PrintChunk("2", "two");

            stackDump(state);

            state.Close();
        }
Пример #19
0
        public void PanicError() // PANIC: unprotected error in call to Lua API (attempt to call a string value)
        {
            state = new Lua();

            LuaFunction oldPanic = state.AtPanic(MyPanicFunc);

            stackDump(state);

            LuaStatus result = state.LoadString("1");

            stackDump(state);

            try
            {
                state.Call(0, 0);
                Assert.Fail("Shoudln't go so far");
            }
            catch (MyPanicException ex)
            { }
            stackDump(state);

            state.Close();
        }
Пример #20
0
        static void Run(string In, string Out, string ChunkName)
        {
            IntPtr L = Lua.NewState();

            Lua.OpenLibs(L);
            Lua.AtPanic(L, (LL) => {
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("\n\nPANIC!");
                Console.ResetColor();
                Console.WriteLine(Lua.ToString(LL, -1));
                Console.ReadKey();
                Environment.Exit(0);
                return(0);
            });

            Lua.RegisterCFunction(L, "_G", "dumpBytecode", (LL) => {
                if (Dumping)
                {
                    int Len            = 0;
                    char *Bytecode     = (char *)Lua.ToLString(L, -1, new IntPtr(&Len)).ToPointer();
                    string BytecodeStr = new string((sbyte *)Bytecode, 0, Len, Encoding.ASCII);
                    File.WriteAllText(Out, BytecodeStr);
                }
                return(0);
            });

            Lua.SetTop(L, 0);
            Lua.GetGlobal(L, "dumpBytecode");
            Lua.GetGlobal(L, "string");
            Lua.PushString(L, "dump");             // Yes, it uses string.dump, and no, i'm not gonna implement proper dump function (lazy)
            Lua.GetTable(L, -2);
            ErrorCheck(L, Lua.LoadBuffer(L, In, ChunkName));
            ErrorCheck(L, Lua.PCall(L, 1, 1, 0));
            Lua.Replace(L, -2);
            ErrorCheck(L, Lua.PCall(L, 1, 0, 0));
            Lua.Close(L);
        }
Пример #21
0
        /// <summary>
        /// Load items
        /// </summary>
        private void LoadItems()
        {
            Log.Write(LogType.Info, "Loading items...");
            Log.Write(LogType.Loading, "Loading item files...");
            String _addonsPath = Configuration.Get <String>("AddonsPath");
            Lua    _lua        = new Lua();

            _lua.DoFile(_addonsPath + "/DefineText.lua");
            _lua.DoFile(_addonsPath + "/DefineBuff.lua");
            _lua.DoFile(_addonsPath + "/jobs.lua");
            _lua.DoFile(_addonsPath + "/propItem.lua");
            LuaTable _items = _lua.GetTable("propItem");

            if (_items != null)
            {
                foreach (DictionaryEntry _entry in _items)
                {
                    Int32 _itemId = (Int32)((Double)_entry.Key);
                    if (this.ItemsData.ContainsKey(_itemId) == false)
                    {
                        try
                        {
                            ItemData _itemData = new ItemData((LuaTable)_entry.Value);
                            if (_itemData != null)
                            {
                                this.ItemsData.Add(_itemId, _itemData);
                            }
                        }
                        catch { }
                    }
                    Log.Write(LogType.Loading, "{0} items loaded...", this.ItemsData.Count);
                }
            }
            _lua.Close();
            Log.Write(LogType.Done, "{0} items loaded!\t\n", this.ItemsData.Count);
        }
Пример #22
0
 // Dispose some scipt
 public void Dispose()
 {
     // KIll lua
     lua.Close();
     lua.Dispose();
 }
Пример #23
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.PanelWidth;
                            try
                            {
                                uint w = (uint)(double)interp["width"];
                                GraphicsData.PanelWidth = w;
                            }
                            catch (Exception)
                            {
                                GraphicsData.PanelWidth = origW;
                                MainWindow.ShowError("Plugin warning: invalid width.\n"
                                                     + "Value " + interp.GetString("width") + " is ignored.");
                            }
                        }
                        #endregion

                        #region height
                        if (interp["height"] != null)
                        {
                            uint origH = GraphicsData.PanelHeight;
                            try
                            {
                                uint h = (uint)(double)interp["height"];
                                GraphicsData.PanelHeight = h;
                            }
                            catch (Exception)
                            {
                                GraphicsData.PanelHeight = 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;
        }
Пример #24
0
        static void Main(string[] args)
        {
            // Prepare console output to a file.
            Directory.CreateDirectory("../Debugging");
            Debug.Listeners.Add(new TextWriterTraceListener(System.Console.Out));
            Debug.Listeners.Add(new TextWriterTraceListener(File.CreateText("../Debugging/output.log")));

            // Load all of the RAW JSON Data into the database.
            var files = Directory.EnumerateFiles(".", "*.json", SearchOption.AllDirectories).ToList();

            files.Sort();
            foreach (var fileName in files)
            {
                Debug.Write(fileName);
                Debug.Write("... ");

                // Load the text and then convert it to a common JSON data format.
                var data = Framework.ToDictionary(File.ReadAllText(fileName));
                if (data == null)
                {
                    Debug.WriteLine("Invalid format!");
                    continue;
                }
                else
                {
                    Debug.WriteLine("");
                }

                // Attempt to merge the data into the Database.
                Framework.Merge(data);
            }
            Debug.WriteLine("Done parsing JSON files...");

            // Load all of the Lua files into the database.
            var luaFiles = Directory.GetFiles(".", "*.lua", SearchOption.AllDirectories).ToList();

            if (luaFiles.Contains(".\\_main.lua"))
            {
                luaFiles.Remove(".\\_main.lua"); // Do not iterate over the header file.
                luaFiles.Sort();
            }
            else
            {
                Debug.WriteLine("Could not find the '_main.lua' header file.");
                Debug.WriteLine("Operation cannot continue without it.");
                Debug.WriteLine("Press Enter to Close.");
                Console.ReadLine();
                return;
            }

            foreach (var fileName in luaFiles)
            {
                //Debug.WriteLine(fileName);
                do
                {
                    try
                    {
                        Lua lua = new Lua();
                        lua.DoFile("./_main.lua");
                        lua.DoFile(fileName);
                        Framework.Merge(lua.GetTable("AllTheThings"));
                        lua.Close();
                        break;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(fileName);
                        Console.WriteLine(e);
                        Console.WriteLine("Press Enter once you have resolved the issue.");
                        Console.ReadLine();
                    }
                }while (true);
            }

            // Now that all of the data and items have been loaded into the Database, let's Process it!
            Framework.Process();

            // Let's do some debugging...
            Debug.Write("There are ");
            Debug.Write(Framework.Items.Count);
            Debug.WriteLine(" Items loaded in the database.");

            // Export all of the data for the Framework.
            Framework.Export();
        }
Пример #25
0
 public void TearDown()
 {
     state.Close();
     state = null;
 }
Пример #26
0
 public void SmokeTest()
 {
     state = new Lua();
     state.Close();
 }
Пример #27
0
 public override void Dispose()
 {
     lua.Close();
 }
Пример #28
0
 public static void Quit()
 {
     _quit = true;
     State.Close();
 }
Пример #29
0
        Tuple <bool, Exception> ReloadScripts()
        {
            try
            {
                if (File.Exists("scripts/main.lua"))
                {
                    if (lua != null)
                    {
                        if (filterFunction != null)
                        {
                            try
                            {
                                LuaFunction finalize = lua.GetFunction("finalize");
                                if (finalize != null)
                                {
                                    finalize.Call();
                                }
                            }
                            catch (Exception ex)
                            {
                                WriteLine("Exception was rised during finalization: " + ex.Message);
                            }
                        }
                        foreach (var c in _checkboxes)
                        {
                            c.Value.Marked = false;
                        }
                        lua.Close();
                    }
                    OnCheckBoxChanged = null;
                    lua = new Lua();

                    lua.RegisterFunction("print", this, typeof(Console).GetMethod("WriteLine"));
                    lua.RegisterFunction("write", this, typeof(Console).GetMethod("Write"));
                    lua["panel"] = controlsPanel;
                    lua.NewTable("checkbox");
                    lua.RegisterFunction("checkbox.add", this, typeof(Console).GetMethod("AddCheckBox"));
                    lua.RegisterFunction("checkbox.get", this, typeof(Console).GetMethod("GetCheckBoxState"));
                    lua["checkbox.height"] = checkBoxHeight;
                    lua.RegisterFunction("checkbox.getgroup", this, typeof(Console).GetMethod("GetCheckBoxGroupState"));
                    lua.NewTable("checkbox.changed");
                    lua.RegisterFunction("checkbox.changed.add", this, typeof(Console).GetMethod("OnCheckBoxChangedAdd"));
                    lua.RegisterFunction("checkbox.changed.remove", this, typeof(Console).GetMethod("OnCheckBoxChangedRemove"));
                    lua.DoFile("scripts/main.lua");
                    filterFunction = lua.GetFunction("main");
                    if (filterFunction != null)
                    {
                        LuaFunction initialize = lua.GetFunction("initialize");
                        if (initialize != null)
                        {
                            initialize.Call();
                        }
                        List <string> remove = new List <string>();
                        foreach (var c in _checkboxes)
                        {
                            if (!c.Value.Marked)
                            {
                                remove.Add(c.Key);
                            }
                        }
                        messageQueue.Enqueue(new Tuple <PumpTaskType, object>(PumpTaskType.RemoveCheckBoxes, remove));
                        semaphore.Release();
                        return(new Tuple <bool, Exception>(true, null));
                    }
                    return(new Tuple <bool, Exception>(false, new InvalidOperationException("Warning: \"main\" function doesn't exist in the main.lua.")));
                }
                return(new Tuple <bool, Exception>(false, new FileNotFoundException("File \"scripts/main.lua\" doesn't exist.", "scripts/main.lua")));
            }
            catch (Exception ex)
            {
                return(new Tuple <bool, Exception>(false, ex));
            }
        }
Пример #30
0
        public static void Main()
        {
            Console.OutputEncoding = new System.Text.UTF8Encoding();



            // 其の壱 : スクリプトを丸々実行する
            //==================================================

            using (var state1 = new Lua())
            {
                Console.WriteLine("[ 其の壱 : スクリプトを丸々実行する ]\n");

                // OpenLibs メソッドの実行を忘れずに
                state1.OpenLibs();
                state1.LoadFile("script1.lua");
                state1.PCall(0, 0, 0);
                state1.Close();

                Console.WriteLine("\n\n");
            }

            //==================================================



            // 其の弐 : Luaステートのスタックを利用する
            //==================================================

            using (var state2 = new Lua())
            {
                Console.WriteLine("[ 其の弐 : Luaステートのスタックを利用する ]\n");

                state2.PushNil();
                state2.PushNumber(2.71);
                state2.PushNumber(3.14);
                state2.PushString("Lua");
                state2.PushBoolean(true);
                PrintStack(state2);
                state2.Close();

                Console.WriteLine("\n\n");
            }

            //==================================================



            // 其の参 : 変数の受け渡し
            //==================================================

            // Luaで定義された変数をC#で取得する
            using (var state3_1 = new Lua())
            {
                Console.WriteLine("[ 其の参(壱) : Luaで定義された変数をC#で取得する ]\n");

                state3_1.OpenLibs();
                state3_1.LoadFile("script3-1.lua");
                state3_1.PCall(0, 0, 0);

                state3_1.GetGlobal("string");
                Console.WriteLine("string = " + state3_1.ToString(-1));
                state3_1.GetGlobal("number");
                Console.WriteLine("number = " + state3_1.ToNumber(-1));
                state3_1.GetGlobal("boolean");
                Console.WriteLine("boolean = " + state3_1.ToBoolean(-1));

                state3_1.Close();

                Console.Write("\n\n\n");
            }

            // C#で設定された変数をLuaで使用する
            using (var state3_2 = new Lua())
            {
                Console.WriteLine("[ 其の参(弐) : C#で設定された変数をLuaで使用する ]\n");

                state3_2.OpenLibs();
                state3_2.LoadFile("script3-2.lua");

                state3_2.PushNumber(56);
                state3_2.SetGlobal("x");
                state3_2.PushNumber(7);
                state3_2.SetGlobal("y");

                state3_2.PCall(0, 0, 0);

                state3_2.Close();

                Console.Write("\n\n\n");
            }

            //==================================================



            // 其の肆 : 関数の受け渡し
            //==================================================

            // Luaで定義された関数をC#で使用する
            using (var state4_1 = new Lua())
            {
                Console.WriteLine("[ 其の肆(壱) : Luaで定義された関数をC#で使用する ]\n");

                state4_1.OpenLibs();
                state4_1.LoadFile("script4-1.lua");
                state4_1.PCall(0, 0, 0);

                state4_1.GetGlobal("arithmetic");
                state4_1.PushNumber(64);
                state4_1.PushNumber(36);

                state4_1.PCall(2, 4, 0);

                Console.WriteLine("sum = " + state4_1.ToNumber(-4));
                Console.WriteLine("dif = " + state4_1.ToNumber(-3));
                Console.WriteLine("mul = " + state4_1.ToNumber(-2));
                Console.WriteLine("div = " + state4_1.ToNumber(-1));

                state4_1.Close();

                Console.Write("\n\n\n");
            }

            // C#で定義された関数をLuaで使用する
            using (var state4_2 = new Lua())
            {
                Console.WriteLine("[ 其の肆(弐) : C#で定義された関数をLuaで使用する ]\n");

                state4_2.OpenLibs();
                state4_2.LoadFile("script4-2.lua");

                state4_2.PushCFunction((IntPtr int_ptr) =>
                {
                    Lua state = Lua.FromIntPtr(int_ptr);
                    double x  = state.ToNumber(-2);
                    double y  = state.ToNumber(-1);
                    state.Pop(-1);
                    state.PushNumber(x + y);
                    state.PushNumber(x - y);
                    state.PushNumber(x * y);
                    state.PushNumber(x / y);
                    return(4);
                });

                state4_2.SetGlobal("arithmetic");
                state4_2.PCall(0, 0, 0);

                state4_2.Close();

                Console.Write("\n\n\n");
            }

            //==================================================



            // 其の伍 : テーブルの受け渡し
            //==================================================

            // Luaで定義されたテーブルをC#で取得する
            using (var state5_1 = new Lua())
            {
                Console.WriteLine("[ 其の伍(壱) : Luaで定義されたテーブルをC#で取得する ]\n");

                state5_1.OpenLibs();
                state5_1.LoadFile("script5-1.lua");
                state5_1.PCall(0, 0, 0);

                state5_1.GetGlobal("table");
                int table_pos = state5_1.GetTop();
                state5_1.GetField(table_pos, "string");
                Console.WriteLine("string = " + state5_1.ToString(-1));
                state5_1.GetField(table_pos, "number");
                Console.WriteLine("number = " + state5_1.ToNumber(-1));
                state5_1.GetField(table_pos, "boolean");
                Console.WriteLine("boolean = " + state5_1.ToBoolean(-1));

                state5_1.Close();

                Console.Write("\n\n\n");
            }

            // C#で設定されたテーブルをLuaで使用する
            using (var state5_2 = new Lua())
            {
                Console.WriteLine("[ 其の伍(弐) : C#で設定されたテーブルをLuaで使用する ]\n");

                state5_2.OpenLibs();
                state5_2.LoadFile("script5-2.lua");

                state5_2.NewTable();
                state5_2.PushString("This is a lua script.");
                state5_2.SetField(-2, "string");
                state5_2.PushNumber(3.14159265);
                state5_2.SetField(-2, "number");
                state5_2.PushBoolean(true);
                state5_2.SetField(-2, "boolean");
                state5_2.SetGlobal("table");

                state5_2.PCall(0, 0, 0);

                state5_2.Close();

                Console.Write("\n\n\n");
            }

            //==================================================



            // 其の陸 : コルーチンを使う
            //==================================================

            using (var state6 = new Lua())
            {
                Console.WriteLine("[ 其の陸 : コルーチンを使う ]\n");

                state6.OpenLibs();
                state6.LoadFile("script6.lua");
                state6.PCall(0, 0, 0);

                Lua coroutine = state6.NewThread();
                coroutine.GetGlobal("co");

                while (coroutine.Resume(null, 0) == LuaStatus.Yield)
                {
                    Console.WriteLine(coroutine.ToString(-1));
                }

                state6.Close();

                Console.Write("\n\n\n");
            }

            //==================================================



            // Luaを使ってオブジェクトの内部状態を更新する
            //==================================================

            Console.WriteLine("[ Luaを使ってオブジェクトの内部状態を更新する ]\n");

            ScriptableObject Object = new ScriptableObject();

            for (int i = 0; i < 30; ++i)
            {
                Object.Update();
            }
            Object.PrintCoordinate();
            for (int i = 0; i < 20; ++i)
            {
                Object.Update();
            }
            Object.PrintCoordinate();
            for (int i = 0; i < 35; ++i)
            {
                Object.Update();
            }
            Object.PrintCoordinate();

            Console.Write("\n\n\n");

            //==================================================
        }