Пример #1
0
		public void TestBinaryLoadFile ()
		{
			using (Lua lua = new Lua ()) {
				lua.LoadCLRPackage ();
				if (IntPtr.Size == 4)
					lua.DoFile ("test_32.luac");
				else
					lua.DoFile ("test_64.luac");

				int width = (int)(double)lua ["width"];
				int height = (int)(double)lua ["height"];
				string message = (string)lua ["message"];
				int color_g	= (int)(double)lua ["color.g"];
				LuaFunction func = (LuaFunction)lua ["func"];
				object[] res = func.Call (12, 34);
				int x = (int)(double)res [0];
				int y = (int)(double)res [1];
				//function func(x,y)
				//	return x,x+y
				//end

				Assert.AreEqual (100, width);
				Assert.AreEqual (200, height);
				Assert.AreEqual ("Hello World!", message);
				Assert.AreEqual (20, color_g);
				Assert.AreEqual (12, x);
				Assert.AreEqual (46, y);
			}
		}
Пример #2
0
        private static void Main()
        {
            Console.Title = "NLua Test Environment";

            object x = 3;
            double y = (double)(int)x;

            string script = "function add(a, b) return a + b, a, b; end\n" +
                            "local function sub(a, b) return a - b; end\n" +
                            "local function mul(a, b) return a * b; end\n" +
                            "local function div(a, b) return a / b; end\n" +
                            "print(\"Adding 1 and 5 gives us \" .. add(1, 5));\n" +
                            "print(\"Subtracting 8 and 2 gives us \" .. sub(8, 2));\n" +
                            "print(\"Multiplying 32 and 1024 gives us \" .. mul(32, 1024));\n" +
                            "print(\"Dividing 8 and 2 gives us \" .. div(8, 2));\n";

            using (dynamic lua = new Lua())
            {
                lua.LoadStandardLibrary(LuaStandardLibraries.Basic);
                lua.DoString("print(\"This confirms the Lua environment has loaded the basic standard library.\\nThe Lua environment is operational.\");");
                lua.DoFile("TestScript.lua");

                lua.v = "test";

                object[] table = lua.x;
            }

            Console.ReadLine();
        }
Пример #3
0
 /// <summary>
 /// 新しくLuaシーンを初期化。
 /// </summary>
 /// <param name="sceneName">シーン名</param>
 /// <param name="luafile">制御するLuaのファイル名</param>
 public LuaScene(string sceneName, string luafile)
     : base()
 {
     LuaScript = new Lua();
     LuaScript["Scenes"] = Scenes.Instance;
     LuaScript.DoFile(luafile);
     ID = sceneName;
 }
Пример #4
0
 public static void DoFile(string path)
 {
     try
     {
         L.DoFile(path);
     }
     catch (Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message);
         System.Windows.Forms.Application.Exit();
     }
 }
Пример #5
0
        public static void Run(string commandname, string[] args, bool fromGroup, string ChatterID, string ChatRoomID)
        {
            try
            {
                using (Lua lua = new Lua())
                {
                    GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions();

                    
                    lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer"));
                    lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented"));
                    lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions"));
                    lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage"));
                    lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage"));
                    //lua.RegisterFunction("convertChatIDtoSteamKit", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("convertChatIDtoSteamKit"));
                    lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName"));
                    lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow"));
                    lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow"));
                    lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand"));
                    lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand"));
                    lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions"));
                    lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName"));
                    lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow"));
                    lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL"));
                    lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer"));
                    lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable"));
                    lua.RegisterFunction("silentFail", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("silentFail"));

                    lua["ChatterID"] = ChatterID;
                    lua["fromGroup"] = fromGroup;
                    lua["ChatRoomID"] = ChatRoomID;
                    lua["args"] = args;
                    for(int i = 1; i < args.Count(); i++)
                    {
                        if (i == 1)
                        {
                            argsJoined = args[i];
                        }
                        else
                        {
                            argsJoined = argsJoined + " " + args[i];
                        }
                    }
                    lua["argsJoined"] = argsJoined;

                    lua.DoFile("lua/commands/" + commandname.Substring(1) + ".lua");
                }
            }
            catch (Exception e)
            {
                Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString());
            }
        }
Пример #6
0
        public static void Run(string scriptname, params string[] args)
        {
            try
            {
                using (Lua lua = new Lua())
                {
                    GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions();


                    lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer"));
                    lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented"));
                    lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions"));
                    lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage"));
                    lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage"));
                    lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName"));
                    lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow"));
                    lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow"));
                    lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand"));
                    lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand"));
                    lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions"));
                    lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName"));
                    lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow"));
                    lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL"));
                    lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer"));
                    lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable"));
                    lua.RegisterFunction("setLoginCredentials", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setLoginCredentials"));
                    lua.RegisterFunction("joinChat", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("joinChat"));
                    lua.RegisterFunction("setAuthCode", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setAuthCode"));
                    lua.RegisterFunction("connect", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("connect"));

                    lua["args"] = args;
                    for (int i = 1; i < args.Count(); i++)
                    {
                        if (i == 1)
                        {
                            argsJoined = args[i];
                        }
                        else
                        {
                            argsJoined = argsJoined + " " + args[i];
                        }
                    }
                    lua["argsJoined"] = argsJoined;

                    lua.DoFile("lua/scripts/" + scriptname + ".lua");
                }
            }
            catch (Exception e)
            {
                Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString());
            }
        }
 public void Load(string location)
 {
     _isLoaded = false;
     try
     {
         var s = _lua.DoFile(location);
         _isLoaded = true;
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Пример #8
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>}]");
            }
        }
Пример #9
0
 /// <summary>
 /// Execute a script from file by name
 /// </summary>
 /// <param name="scriptName"></param>
 public static bool executeScript(string scriptName)
 {
     Lua lua = new Lua();
     lua.LoadCLRPackage();
     lua.DoString(@" import ('TextRPG', 'TextRPG')
        import ('System') ");
     try
     {
         var x = lua.DoFile(scriptName+".lua");
         GUI.Instance.appendToOutput(x.ToString());
         return true;
     }
     catch (Exception e)
     {
         return false;
     }
 }
Пример #10
0
        /// <summary>
        /// A label for displaying values obtained through Lua scripts.
        /// </summary>
        /// <param name="filePath">The path to the Lua script. The script must contain a GetValue() function, which returns the desired text to be displayed.</param>
        /// <param name="lua">Obtained by calling GetLua() on a WatchManager32Bit.</param>
        public LuaWatch(string filePath, Lua.Lua lua)
        {
            NLua.Lua n = new NLua.Lua();
            n.LoadCLRPackage();
            n.DoString("import ('DeSmuME_Watch', 'DeSmuME_Watch.Lua')");

            n.DoFile(filePath);
            luaGetValue = n.GetFunction("GetValue");
            this.lua    = lua;
            n["WATCH"]  = lua;

            if (luaGetValue == null)
            {
                throw new Exception("Lua script could not be loaded. Make sure it contains the function GetValue().");
            }

            this.AutoSize = true;
            this.SetText("?");
        }
Пример #11
0
        public override IEnumerable<Kbtter4Plugin> Load(Kbtter instance, IList<string> filenames)
        {
            var list = new List<Kbtter4LuaPlugin>();
            var files = filenames.Where(p => p.EndsWith(".lua"));
            foreach (var i in files)
            {
                try
                {
                    Lua l = new Lua();
                    l.LoadCLRPackage();
                    l["Kbtter4"] = new Kbtter4PluginProvider(instance);
                    l.DoFile(i);
                    list.Add(new Kbtter4LuaPlugin(l,instance));
                }
                catch (Exception e)
                {
                    instance.LogError("Luaプラグイン読み込み中にエラーが発生しました : " + e.Message);
                }
            }

            return list;
        }
Пример #12
0
        public static Option<Exception> Execute(string pathOrLiteral, Dictionary<string, object> args)
        {
            using(var state = new Lua()) {
                Exception internalEx = null;
                state.HookException += (s, e) => internalEx = e.Exception;

                foreach(var ele in args) {
                    state[ele.Key] = ele.Value;
                }

                try {
                    if(IsValidLuaScriptPath(pathOrLiteral)) {
                        state.DoFile(pathOrLiteral);
                    } else {
                        state.DoString(pathOrLiteral);
                    }
                    return internalEx != null ? Option.New(internalEx) : Option.New<Exception>();
                } catch (TargetInvocationException ex) {
                    return Option.New(ex.InnerException);
                } catch(Exception ex) {
                    return Option.New(ex);
                }
            }
        }
Пример #13
0
 /// <summary>
 /// Run the specified script.
 /// </summary>
 /// <param name="scriptFile">Script file name</param>
 public void RunScript(string scriptFile)
 {
     if (File.Exists(scriptFile))
     {
         try
         {
             using (NLua.Lua lua = new NLua.Lua())
             {
                 lua.LoadCLRPackage();
                 _luaAPI.RegisterFunctions(lua);
                 lua.DoFile(scriptFile);
                 LuaFunction fnc = lua.GetFunction("on_Run");
                 if (fnc != null)
                 {
                     fnc.Call();
                 }
             }
         }
         catch (LuaScriptException e)
         {
             MessageBox.Show(e.Message, Resources.ScriptException, MessageBoxButtons.OK);
         }
     }
 }
Пример #14
0
        public Service()
        {
            this.LastAlert   = new DateTime(1970, 01, 01, 0, 0, 0);
            this.LastENumber = "";
            try {
                FeuerwehrCloud.Helper.Logger.WriteLine("|  *** Initializing NLua...");
                lua = new NLua.Lua();
                lua.LoadCLRPackage();
                lua ["Service"] = this;
            } catch (Exception ex) {
                if (ex.GetType().ToString() == "System.DllNotFoundException" && System.Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    //
                }
                else
                {
                    //
                }
                FeuerwehrCloud.Helper.Logger.WriteLine(ex.ToString());
                return;
            }


            System.IO.File.Delete("versions.txt");
            System.IO.File.AppendAllText("versions.txt", System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetName().CodeBase) + ":" + Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Build.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString() + "\r\n");

            var plugins = System.IO.Directory.EnumerateFiles("./plugins", "FeuerwehrCloud.*.*.dll");

            //FeuerwehrCloud.Plugin.IPlugin c = new  FeuerwehrCloud.Input.SMTP.SMTPSever ();
            foreach (string currentFile in plugins)
            {
                try {
                    if (!System.IO.File.Exists(currentFile + ".disabled"))
                    {
                        var DLL    = Assembly.LoadFile(currentFile);
                        var dllVer = DLL.GetName().Version;
                        System.IO.File.AppendAllText("versions.txt", System.IO.Path.GetFileNameWithoutExtension(currentFile) + ":" + dllVer.Major.ToString() + "." + dllVer.Minor.ToString() + "." + dllVer.Build.ToString() + "." + dllVer.Revision.ToString() + "\r\n");
                        foreach (Type type in DLL.GetExportedTypes())
                        {
                            FeuerwehrCloud.Plugin.IPlugin c;
                            try {
                                c = (FeuerwehrCloud.Plugin.IPlugin)Activator.CreateInstance(type);
                                lua[System.IO.Path.GetFileNameWithoutExtension(currentFile).Replace(".", "_")] = c;
                                //lua[System.IO.Path.GetFileNameWithoutExtension (currentFile)] = c;
                                lua.DebugHook += HandleDebugHook;
                                lua.RegisterFunction(System.IO.Path.GetFileNameWithoutExtension(currentFile).Replace(".", "_") + "_Execute", c, c.GetType().GetMethod("Execute"));
                                if (c.Initialize(this))
                                {
                                    //FeuerwehrCloud.Helper.Logger.WriteLine(">>>>"+System.IO.Path.GetFileNameWithoutExtension (currentFile));
                                    PlugIns.Add(System.IO.Path.GetFileNameWithoutExtension(currentFile), c);
                                    c.Event += delegate(object sender, object[] list) {
                                        /*Xamarin.Insights.Track ("Event", new System.Collections.Generic.Dictionary<string, string> {
                                         *      {"ModuleName", c.Name },
                                         *      {"ServiceType", c.ServiceType.ToString()},
                                         *      {"NextAction", sender.ToString() + ".lua" }
                                         * });*/

                                        lua["response"] = list;
                                        switch (c.ServiceType)
                                        {
                                        case FeuerwehrCloud.Plugin.ServiceType.input:
                                            if (list [0] == "pictures")
                                            {
                                                try {
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("3||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                    lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua");
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("3||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                }
                                                catch (Exception ex) {
                                                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                                                }
                                            }
                                            else
                                            if (list [0] == "text")
                                            {
                                                try {
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("4||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                    lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua");
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("4||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                }
                                                catch (Exception ex) {
                                                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                                                }
                                            }
                                            break;

                                        case FeuerwehrCloud.Plugin.ServiceType.processor:
                                            if (list [0] == "pictures")
                                            {
                                                try {
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("1||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                    lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua");
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("1||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                }
                                                catch (Exception ex) {
                                                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                                                }
                                            }
                                            else
                                            if (list [0] == "text")
                                            {
                                                try {
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("5||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                    lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua");
                                                    //FeuerwehrCloud.Helper.Logger.WriteLine("5||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                }
                                                catch (Exception ex) {
                                                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                                                    try {
                                                    }
                                                    catch (Exception ex2) {
                                                        var smtpClient = new System.Net.Mail.SmtpClient();
                                                        smtpClient.Host           = "feuerwehrcloud.de";
                                                        smtpClient.Port           = 25;
                                                        smtpClient.EnableSsl      = false;
                                                        smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                                                        var smtp        = smtpClient;
                                                        var mailMessage = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**");
                                                        mailMessage.Subject = "[FeuerwehrCloud] EXCEPTION AT " + System.Environment.MachineName;
                                                        mailMessage.Body    = FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex);
                                                        using (var message = mailMessage)
                                                            smtp.Send(message);
                                                    }
                                                }
                                            }
                                            break;

                                        case FeuerwehrCloud.Plugin.ServiceType.output:
                                            try {
                                                //FeuerwehrCloud.Helper.Logger.WriteLine("2||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                                lua.DoFile(sender.ToString() + ".lua");
                                                //FeuerwehrCloud.Helper.Logger.WriteLine("2||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua");
                                            } catch (Exception ex) {
                                                FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                                            }
                                            break;
                                        }
                                        //FeuerwehrCloud.Helper.Logger.WriteLine(list[0].ToString());
                                    };
                                }
                            } catch (Exception ex) {
                                FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                            }
                        }
                    }
                } catch (Exception ex) {
                    FeuerwehrCloud.Helper.Logger.WriteLine("************ ERRROR ***************");
                    FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                }
            }
            FeuerwehrCloud.Helper.Logger.WriteLine("|  Loaded plugins: " + PlugIns.Count.ToString());

            lua ["PlugIns"] = PlugIns;
            lua.DoFile("init_complete.lua");
            FeuerwehrCloud.Helper.Logger.WriteLine("|  Initialisation complete. System started.");
            FeuerwehrCloud.Helper.Logger.WriteLine("`·--- Startup complete. ----------------------- ----- --  -");
        }
Пример #15
0
        /// <summary>
        /// Load a single script from the specified manifest.
        /// </summary>
        private void LoadSingleScript(string path, ScriptManifest manifest)
        {
            string scriptFile = Path.Combine(path, manifest.ScriptFile);

            NLua.Lua lua = new NLua.Lua();
            lua.LoadCLRPackage();
            _luaAPI.RegisterFunctions(lua);
            bool success = true;

            try
            {
                lua.DoFile(scriptFile);
                LuaFunction fnc = lua.GetFunction("on_load");
                if (fnc != null)
                {
                    object[] res = fnc.Call();
                    if (res != null && res.Length == 1)
                    {
                        success = Convert.ToBoolean(res[0]);
                    }
                }

                // Cache this script object for event callbacks if the
                // init function returns success.
                if (success)
                {
                    if (_scriptObjects.ContainsKey(scriptFile))
                    {
                        // BUGBUG: What if we have scripts that register events? We need to tell
                        // them to unregister first. Add an interface for this.
                        NLua.Lua oldScript = _scriptObjects[scriptFile];
                        oldScript.Dispose();

                        _scriptObjects.Remove(scriptFile);
                    }
                    _scriptObjects.Add(scriptFile, lua);
                }

                if (manifest.InstallToToolbar)
                {
                    ToolbarDataItem item = new ToolbarDataItem
                    {
                        type    = "button",
                        name    = "Script",
                        label   = manifest.Name,
                        tooltip = manifest.Description,
                        data    = scriptFile,
                        image   = manifest.IconFile
                    };
                    CRToolbarItemCollection.DefaultCollection.Add(item);
                }
            }
            catch (Exception e)
            {
                LogFile.WriteLine("Error loading script {0} : {1}", scriptFile, e.Message);
                success = false;
            }
            if (success)
            {
                LogFile.WriteLine("Loaded and initialised script {0}", scriptFile);
            }
            else
            {
                lua.Dispose();
            }
        }
 protected object DoFile(string file)
 {
     return(_lua.DoFile(file.Replace("\\", "\\\\")));
 }
Пример #17
0
 public object[] ExecScriptFile(string file_name)
 {
     return(m_LuaState.DoFile(file_name));
 }
        /// <summary>
        /// Create a building.
        /// </summary>
        /// <param name="key">The key of the building to create as defined in its .lua file</param>
        /// <param name="position">Position, in pixels, to create the building at</param>
        /// <returns></returns>
        public static Building CreateBuilding(string key, Vector2 position)
        {
            Building Output = new Building();

            lua = new Lua();
            lua.DoFile(GetPath(key));

            if ((string)lua["type"] == "building")
            {
                Output.Name = (string)lua["name"];
                Output.Description = (string)lua["description"];
                //Output.Position = position;
                //Output.Rotation = (float)(double)lua["rotation"];

                #region Drawables
                LuaTable drawables = lua.GetTable("drawableParts");
                Output.BuildingParts = new List<DrawableBuildingPart>(drawables.Values.Count);

                foreach (LuaTable table in drawables.Values)
                {

                    DrawableBuildingPart part = new DrawableBuildingPart();
                    part.Image = Art.LoadImage((string)table["imagePath"]);
                    part.Alpha = (float)(double)table["alpha"];
                    part.Tint = LuaHelper.LuaToColor((LuaTable)table["tint"]);
                    part.Offset = new Vector2((int)(double)table["offsetX"], (int)(double)table["offsetY"]);
                    part.Rotation = (float)(double)table["rotation"];

                    Output.BuildingParts.Add(part);
                    //part.Offset = new Vector2(
                }
                #endregion

                #region Physics
                Output.Body = BodyFactory.CreateBody(World);
                Output.Body.BodyType = BodyType.Dynamic;
                Output.Body.FixedRotation = true;
                Output.Body.Position = Physics.ToMetres(position);

                LuaTable physicsShapes = lua.GetTable("physicsShapes");
                LuaTable rectangles = (LuaTable)physicsShapes["rectangles"];
                foreach (LuaTable table in rectangles.Values)
                {
                    Vector2 centre = new Vector2(
                        Physics.ToMetres((float)(double)table["centreX"]),
                        Physics.ToMetres((float)(double)table["centreY"])
                        );
                    float width = Physics.ToMetres((float)(double)table["width"]);
                    float height = Physics.ToMetres((float)(double)table["height"]);
                    //float rotation = (float)(double)table["rotation"];
                    //Body body = BodyFactory.CreateRectangle(World, width, height, 1, centre);
                    Fixture fix = FixtureFactory.AttachRectangle(width, height, 1, centre, Output.Body);
                    //Fixture fix = new Fixture(
                    //FixtureFactory.
                    //FixtureDef
                    //fix.
                    //body.Rotation = rotation;
                    //Body
                }
                LuaTable circles = (LuaTable)physicsShapes["circles"];
                foreach (LuaTable table in circles)
                {
                    Vector2 centre = new Vector2(
                        Physics.ToMetres((float)(double)table["centreX"]),
                        Physics.ToMetres((float)(double)table["centreY"])
                        );
                    float radius = Physics.ToMetres((float)(double)table["radius"]);
                }
                #endregion
            }
            //lua.

            Buildings.Add(Output);
            return Output;
        }
Пример #19
0
        public override void Run(string[] arguments)
        {
            // Correcting path => base path is package path
            arguments[0] = Path.Combine(Package.Directory.FullName + Path.DirectorySeparatorChar, arguments[0]);

            using (Lua lua = new Lua())
            {
                lua.LoadCLRPackage();

                lua.DoString("import(\"craftitude\")"); // Load craftitude assembly into Lua.
                lua.RegisterFunction("GetPlatformString", this, this.GetType().GetMethod("GetPlatformString"));
                lua.RegisterFunction("GetProfile", this, this.GetType().GetMethod("GetProfile"));
                lua.RegisterFunction("GetPackage", this, this.GetType().GetMethod("GetPackage"));
                lua.RegisterFunction("GetProfilePath", this, this.GetType().GetMethod("GetProfilePath"));
                lua.RegisterFunction("GetPackagePath", this, this.GetType().GetMethod("GetPackagePath"));
                lua.DoString(@"
            local mt = { }
            local methods = { }
            function mt.__index(userdata, k)
            if methods[k] then
            return methods[k]
            else
            return rawget(userdata, ""_array"")[k]
            end
            end

            function mt.__newindex(userdata, k, v)
            if methods[k] then
            error ""can't assign to method!""
            else
            rawget(userdata, ""_array"")[k] = v
            end
            end");
                lua.DoString(@"
            function import_plugin(assemblyName, namespace)
            import(Path.Combine(GetPluginsDir(), assemblyName))
            import(namespace)
            end");
                lua.DoString(@"function install_plugin(dllPath, assemblyName)
            System.IO.File.Copy(dllPath, Path.Combine(GetPluginsDir(), assemblyName .. "".dll""))
            end");
                lua.DoString(@"function uninstall_plugin(assemblyName)
            System.IO.File.Delete(Path.Combine(GetPluginsDir(), assemblyName .. "".dll""))
            end");
                lua.DoFile(Path.Combine(Package.Path + Path.DirectorySeparatorChar, arguments[0].Replace('/', Path.DirectorySeparatorChar)));
                lua.GetFunction(arguments[1]).Call();
            }
        }
Пример #20
0
        public static void install_mod_from_metafile(ModConfig config, int id = 0)
        {
            Directory.CreateDirectory(Globals.temporary_path);
            /*
             * Runs the installation thread.
             */
            if (config.requires_brawlex == true)
            {
                if (!File.Exists(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/CSSRoster.dat")))
                {
                    TopMostMessageBox.Show("BrawlEX + CSS Extension is required for this mod to install.", "BrawlEX Error");

                    return;
                }
                if (!Directory.Exists(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/CosmeticConfig")));
                {
                    Directory.CreateDirectory(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/CosmeticConfig"));
                }
                if (!Directory.Exists(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/CSSSlotConfig")));
                {
                    Directory.CreateDirectory(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/CSSSlotConfig"));
                }
                if (!Directory.Exists(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/FighterConfig")));
                {
                    Directory.CreateDirectory(Path.Combine(SDCard.sd_card_path,
                        "private/wii/app/RSBE/pf/BrawlEx/FighterConfig"));
                }
                if (!Directory.Exists(Path.Combine(SDCard.sd_card_path, "private/wii/app/RSBE/pf/BrawlEx/SlotConfig")));
                {
                    Directory.CreateDirectory(Path.Combine(SDCard.sd_card_path,
                        "private/wii/app/RSBE/pf/BrawlEx/SlotConfig"));
                }
            }
            var state = new Lua();
            state.LoadCLRPackage();
            Globals.current_mod_config = config;
            state.DoFile(Path.Combine(Globals.AssemblyDirectory, "data/lua/init.lua"));
            state.DoFile(Path.Combine(Globals.temporary_path, config.install_script));
            Directory.CreateDirectory(Path.Combine(new string[] {SDCard.sd_card_mod_store_path, config.name}));
            var json_contents = File.ReadAllText(Path.Combine(Globals.temporary_path, "mod.json"));
            var mod = JsonConvert.DeserializeObject<ModConfig>(json_contents);
            mod.id = id;
            if (id != 0)
            {
                mod.online_mod = true;
            }
            var content = JsonConvert.SerializeObject(mod, Formatting.Indented);
            File.WriteAllText(Path.Combine(Globals.temporary_path, "mod.json"), content);
            File.Copy(Path.Combine(Globals.temporary_path, "mod.json"),
                Path.Combine(new string[] {SDCard.sd_card_mod_store_path, config.name, "mod.json"}));
            File.Copy(Path.Combine(Globals.temporary_path, "init.lua"),
                Path.Combine(new string[] { SDCard.sd_card_mod_store_path, config.name, "init.lua" }));
        }
Пример #21
0
 public static void update_mod_from_metafile(ModConfig config, int id = 0)
 {
     Directory.CreateDirectory(Globals.temporary_path);
     /*
      * Runs the installation thread.
      */
     var state = new Lua();
     state.LoadCLRPackage();
     state.DoFile(Path.Combine(Globals.AssemblyDirectory, "data/lua/init.lua"));
     state.DoFile(Path.Combine(Globals.temporary_path, config.install_script));
     Directory.CreateDirectory(Path.Combine(new string[] { SDCard.sd_card_mod_store_path, config.name }));
     var json_contents = File.ReadAllText(Path.Combine(Globals.temporary_path, "mod.json"));
     var mod = JsonConvert.DeserializeObject<ModConfig>(json_contents);
     mod.id = id;
     var content = JsonConvert.SerializeObject(mod, Formatting.Indented);
     File.WriteAllText(Path.Combine(Globals.temporary_path, "mod.json"), content);
     File.Copy(Path.Combine(Globals.temporary_path, "mod.json"),
         Path.Combine(new string[] { SDCard.sd_card_mod_store_path, config.name, "mod.json" }));
 }
        public Task <Module[]> GetInstalledAircraftModulesAsync()
        {
            Tracer.Info("Searching DCS for installed modules.");

            var settingsService = _container.Resolve <ISettingsService>();
            var install         = settingsService.SelectedInstall;

            if (!install.IsValidInstall)
            {
                Tracer.Info("Current install is invalid, aborting...");
                return(Task.FromResult(_modules.Values.ToArray()));
            }

            return(Task.Run(() =>
            {
                var autoUpdateModules = new List <string>(install.Modules)
                {
                    "Su-25T",
                    "TF-51D"
                };

                var aircraftFolders = Directory.GetDirectories(Path.Combine(install.Directory, "Mods//aircraft"));

                foreach (var folder in aircraftFolders)
                {
                    using (var lua = new NLua.Lua())
                    {
                        lua.State.Encoding = Encoding.UTF8;

                        var entryPath = Path.Combine(folder, "entry.lua");

                        lua.DoString(
                            @"function _(s) return s end
                                function _(s) return s end
                                function mount_vfs_liveries_path() end
                                function mount_vfs_texture_path() end
                                function mount_vfs_sound_path() end
                                function mount_vfs_model_path() end
                                function make_view_settings() end
                                function set_manual_path() end
                                function dofile() end
                                function plugin_done() end
                                function make_flyable() end
                                function MAC_flyable() end
                                function turn_on_waypoint_panel() end
                                AV8BFM = {}
                                F86FM = {}
                                F5E = {}
                                FA18C = {}
                                F15FM = {}
                                F16C = {}
                                FM = {}
                                M2KFM = {}
                                Mig15FM = {}
                                MIG19PFM = {}
                                SA342FM = {}
                                JF17_FM = {}
                                function add_plugin_systems() end
                                " + $"__DCS_VERSION__ = \"{install.Version}\"");

                        var directoryName = Path.GetDirectoryName(folder);

                        lua.DoString($"current_mod_path = \"{folder.Replace("\\", "\\\\")}\"");

                        var moduleId = string.Empty;
                        var skinsPath = string.Empty;
                        var displayName = string.Empty;

                        lua["declare_plugin"] = new Action <string, LuaTable>((id, description) =>
                        {
                            if (description.Keys.OfType <string>().All(k => k != "installed" && k != "update_id"))
                            {
                                return;
                            }

                            moduleId =
                                description.Keys.OfType <string>().All(k => k != "update_id")
                                    ? description["fileMenuName"]?.ToString()
                                    : description["update_id"]?.ToString();

                            var skinsTable = description["Skins"] as LuaTable;

                            if (skinsTable != null)
                            {
                                skinsPath = ((LuaTable)skinsTable[1])["dir"].ToString();
                            }

                            var missionsTable = description["Missions"] as LuaTable;

                            if (missionsTable != null)
                            {
                                displayName = ((LuaTable)missionsTable[1])["name"].ToString();
                            }
                        });

                        var makeFlyableAction = new Action <string, string, LuaTable, string>((a, b, c, d) =>
                        {
                            if (displayName.Contains("_hornet"))
                            {
                                displayName = displayName.Split('_')[0];
                            }

                            if (_modules.ContainsKey($"{moduleId}_{a}"))
                            {
                                return;
                            }

                            if (!string.IsNullOrEmpty(moduleId) && autoUpdateModules.Contains(moduleId) && moduleId != "FC3")
                            {
                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName}.");
                            }
                            else if (moduleId == "FC3")
                            {
                                //fc3Added = true;

                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    IsFC3 = true,
                                    FC3ModuleId = a,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                };

                                _modules.Add($"{moduleId}_{a}", module);

                                Tracer.Debug($"Found module {displayName} {a}.");
                            }
                            else
                            {
                                Tracer.Debug($"Not loading module '{moduleId} - {displayName}' parameters ('{a}', '{b}', '{d}'.");
                            }
                        });

                        lua["make_flyable"] = makeFlyableAction;
                        lua["MAC_flyable"] = makeFlyableAction;

                        try
                        {
                            lua.DoFile(entryPath);
                        }
                        catch (Exception e)
                        {
                            Tracer.Error(e.Message);
                        }
                    }
                }

                return _modules.Values.ToArray();
            }));
        }
Пример #23
0
 public override int Load(IList<string> filenames)
 {
     var err = 0;
     var list = filenames.Where(p => p.EndsWith(".lua"));
     foreach (var i in list)
     {
         var l = new Lua();
         l.LoadCLRPackage();
         l["Kbtter3"] = ep;
         try
         {
             luas.Add(l);
             l.DoFile(i);
         }
         catch (Exception e)
         {
             kbtter.LogError(string.Format("Luaプラグインローダー\n{0}の読み込み中にエラーが発生しました \n{1}", i, e.Message));
             err++;
         }
     }
     return err;
 }
Пример #24
0
        /// <summary>
        /// Load a single script from the specified manifest.
        /// </summary>
        private void LoadSingleScript(string path, ScriptManifest manifest)
        {
            string scriptFile = Path.Combine(path, manifest.ScriptFile);

            NLua.Lua lua = new NLua.Lua();
            lua.LoadCLRPackage();
            _luaAPI.RegisterFunctions(lua);
            bool success = true;
            try
            {
                lua.DoFile(scriptFile);
                LuaFunction fnc = lua.GetFunction("on_load");
                if (fnc != null)
                {
                    object[] res = fnc.Call();
                    if (res != null && res.Length == 1)
                    {
                        success = Convert.ToBoolean(res[0]);
                    }
                }

                // Cache this script object for event callbacks if the
                // init function returns success.
                if (success)
                {
                    if (_scriptObjects.ContainsKey(scriptFile))
                    {
                        // BUGBUG: What if we have scripts that register events? We need to tell
                        // them to unregister first. Add an interface for this.
                        NLua.Lua oldScript = _scriptObjects[scriptFile];
                        oldScript.Dispose();

                        _scriptObjects.Remove(scriptFile);
                    }
                    _scriptObjects.Add(scriptFile, lua);
                }

                if (manifest.InstallToToolbar)
                {
                    ToolbarDataItem item = new ToolbarDataItem
                    {
                        type = "button",
                        name = "Script",
                        label = manifest.Name,
                        tooltip = manifest.Description,
                        data = scriptFile,
                        image = manifest.IconFile
                    };
                    CRToolbarItemCollection.DefaultCollection.Add(item);
                }
            }
            catch (Exception e)
            {
                LogFile.WriteLine("Error loading script {0} : {1}", scriptFile, e.Message);
                success = false;
            }
            if (success)
            {
                LogFile.WriteLine("Loaded and initialised script {0}", scriptFile);
            }
            else
            {
                lua.Dispose();
            }
        }
Пример #25
0
 public void DoFile(string fileName)
 {
     _lua.DoFile(fileName);
 }
        public static void Scan()
        {
            string fullPath = Environment.CurrentDirectory;
            fullPath = Path.Combine(fullPath, Constants.DataDirectory, baseBuildingsDirectory);
            //Console.WriteLine(fullPath);

            DirectoryInfo dir = new DirectoryInfo(fullPath);

            foreach (var file in dir.GetFiles("*.lua"))
            {
                lua = new Lua();
                lua.DoFile(file.FullName);
                if ((string)lua["type"] == "building")
                {
                    string key = (string)lua["key"];
                    Console.WriteLine(key);
                    //Console.WriteLine(file.FullName);
                    InitPaths.Add(key, file.FullName);
                }
                //lua.Close();
            }
            //Console.WriteLine("foo!");
        }
Пример #27
0
		public static void LoadRecipes()
		{
			using (Lua lua = new Lua())
			{
				List<String> luaFiles = getAllLuaFiles().ToList();
				List<String> luaDirs = getAllModDirs().ToList();

				//Add all these files to the Lua path variable
				foreach (String dir in luaDirs)
				{
					AddLuaPackagePath(lua, dir); //Prototype folder matches package hierarchy so this is enough.
				}

				AddLuaPackagePath(lua, Path.Combine(luaDirs[0], "lualib")); //Add lualib dir

				String dataloaderFile = luaFiles.Find(f => f.EndsWith("dataloader.lua"));
				String autoplaceFile = luaFiles.Find(f => f.EndsWith("autoplace_utils.lua"));

				List<String> itemFiles = luaFiles.Where(f => f.Contains("prototypes" + Path.DirectorySeparatorChar + "item")).ToList();
				itemFiles.AddRange(luaFiles.Where(f => f.Contains("prototypes" + Path.DirectorySeparatorChar + "fluid")).ToList());
				itemFiles.AddRange(luaFiles.Where(f => f.Contains("prototypes" + Path.DirectorySeparatorChar + "equipment")).ToList());
				List<String> recipeFiles = luaFiles.Where(f => f.Contains("prototypes" + Path.DirectorySeparatorChar + "recipe")).ToList();
				List<String> entityFiles = luaFiles.Where(f => f.Contains("prototypes" + Path.DirectorySeparatorChar + "entity")).ToList();
				
				try
				{
					lua.DoFile(dataloaderFile);
				}
				catch (Exception e)
				{
					failedFiles[dataloaderFile] = e;
					return; //There's no way to load anything else without this file.
				}
				try
				{
					lua.DoFile(autoplaceFile);
				}
				catch (Exception e)
				{
					failedFiles[autoplaceFile] = e;
				}
				foreach (String f in itemFiles.Union(recipeFiles).Union(entityFiles))
				{
					try
					{
						lua.DoFile(f);
					}
					catch (NLua.Exceptions.LuaScriptException e)
					{
						failedFiles[f] = e;
					}
				}

				foreach (String type in new List<String> { "item", "fluid", "capsule", "module", "ammo", "gun", "armor", "blueprint", "deconstruction-item" })
				{
					InterpretItems(lua, type);
				}

				LuaTable recipeTable = lua.GetTable("data.raw")["recipe"] as LuaTable;
				if (recipeTable != null)
				{
					var recipeEnumerator = recipeTable.GetEnumerator();
					while (recipeEnumerator.MoveNext())
					{
						InterpretLuaRecipe(recipeEnumerator.Key as String, recipeEnumerator.Value as LuaTable);
					}
				}

				LuaTable assemblerTable = lua.GetTable("data.raw")["assembling-machine"] as LuaTable;
				if (assemblerTable != null)
				{
					var assemblerEnumerator = assemblerTable.GetEnumerator();
					while (assemblerEnumerator.MoveNext())
					{
						InterpretAssemblingMachine(assemblerEnumerator.Key as String, assemblerEnumerator.Value as LuaTable);
					}
				}

				LuaTable furnaceTable = lua.GetTable("data.raw")["furnace"] as LuaTable;
				if (furnaceTable != null)
				{
					var furnaceEnumerator = furnaceTable.GetEnumerator();
					while (furnaceEnumerator.MoveNext())
					{
						InterpretFurnace(furnaceEnumerator.Key as String, furnaceEnumerator.Value as LuaTable);
					}
				}

				LuaTable minerTable = lua.GetTable("data.raw")["mining-drill"] as LuaTable;
				if (minerTable != null)
				{
					var minerEnumerator = minerTable.GetEnumerator();
					while (minerEnumerator.MoveNext())
					{
						InterpretMiner(minerEnumerator.Key as String, minerEnumerator.Value as LuaTable);
					}
				}

				LuaTable resourceTable = lua.GetTable("data.raw")["resource"] as LuaTable;
				if (resourceTable != null)
				{
					var resourceEnumerator = resourceTable.GetEnumerator();
					while (resourceEnumerator.MoveNext())
					{
						InterpretResource(resourceEnumerator.Key as String, resourceEnumerator.Value as LuaTable);
					}
				}

				LuaTable moduleTable = lua.GetTable("data.raw")["module"] as LuaTable;
				if (moduleTable != null)
				{
					foreach (String moduleName in moduleTable.Keys)
					{
						InterpretModule(moduleName, moduleTable[moduleName] as LuaTable);
					}
				}

				UnknownIcon = LoadImage("UnknownIcon.png");

				LoadLocaleFiles();

				LoadItemNames("item-name");
				LoadItemNames("fluid-name");
				LoadItemNames("entity-name");
				LoadItemNames("equipment-name");
				LoadRecipeNames();
				LoadEntityNames();
				LoadModuleNames();
			}
		}
Пример #28
0
        private void run_lua_button_Click(object sender, EventArgs e)
        {
            var file_dialog = new OpenFileDialog();
            file_dialog.Filter = "Lua File (*.lua)|*.lua";
            file_dialog.ShowDialog();
            if (file_dialog.FileName == null)
            {
                return;
            }
            var lua = new Lua();
            lua.LoadCLRPackage();

            lua.DoFile(Path.Combine(Application.StartupPath, "data/lua/init.lua"));
            lua.DoFile(file_dialog.FileName);
            Console.WriteLine("Running Lua...");
        }
Пример #29
0
 /// <summary>
 /// Run the specified script.
 /// </summary>
 /// <param name="scriptFile">Script file name</param>
 public void RunScript(string scriptFile)
 {
     if (File.Exists(scriptFile))
     {
         try
         {
             using (NLua.Lua lua = new NLua.Lua())
             {
                 lua.LoadCLRPackage();
                 _luaAPI.RegisterFunctions(lua);
                 lua.DoFile(scriptFile);
                 LuaFunction fnc = lua.GetFunction("on_Run");
                 if (fnc != null)
                 {
                     fnc.Call();
                 }
             }
         }
         catch (LuaScriptException e)
         {
             MessageBox.Show(e.Message, Resources.ScriptException, MessageBoxButtons.OK);
         }
     }
 }
        public Task <Module[]> GetInstalledAircraftModulesAsync()
        {
            Tracer.Info("Searching DCS for installed modules.");
#pragma warning disable CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
            return(Task.Run(async() =>
#pragma warning restore CS1998 // This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
            {
                var settingsService = _container.Resolve <ISettingsService>();
                var modules = new List <Module>();
                var install = settingsService.SelectedInstall;
                var autoupdateModules = new List <string>(install.Modules);

                autoupdateModules.Add("Su-25T");
                autoupdateModules.Add("TF-51D");

                if (!install.IsValidInstall)
                {
                    return modules.ToArray();
                }

                var aircraftFolders = Directory.GetDirectories(Path.Combine(install.Directory, "Mods//aircraft"));

                foreach (var folder in aircraftFolders)
                {
                    using (var lua = new NLua.Lua())
                    {
                        lua.State.Encoding = Encoding.UTF8;

                        var entryPath = Path.Combine(folder, "entry.lua");

                        lua.DoString(
                            @"function _(s) return s end
                                function _(s) return s end
                                function mount_vfs_liveries_path() end
                                function mount_vfs_texture_path() end
                                function mount_vfs_sound_path() end
                                function mount_vfs_model_path() end
                                function make_view_settings() end
                                function set_manual_path() end
                                function dofile() end
                                function plugin_done() end
                                function make_flyable() end
                                AV8BFM = {}
                                F86FM = {}
                                F5E = {}
                                FA18C = {}
                                F15FM = {}
                                FM = {}
                                M2KFM = {}
                                Mig15FM = {}
                                MIG19PFM = {}
                                SA342FM = {}
                                " + $"__DCS_VERSION__ = \"{install.Version}\"");

                        var directoryName = Path.GetDirectoryName(folder);

                        lua.DoString($"current_mod_path = \"{folder.Replace("\\", "\\\\")}\"");

                        var moduleId = string.Empty;
                        var skinsPath = string.Empty;
                        var displayName = string.Empty;

                        lua["declare_plugin"] = new Action <string, LuaTable>((id, description) =>
                        {
                            if (description.Keys.OfType <string>().All(k => k != "installed" && k != "update_id"))
                            {
                                return;
                            }

                            if (description.Keys.OfType <string>().All(k => k != "update_id"))
                            {
                                moduleId = description["fileMenuName"]?.ToString();
                            }
                            else
                            {
                                moduleId = description["update_id"]?.ToString();
                            }

                            skinsPath = ((LuaTable)((LuaTable)description["Skins"])[1])["dir"].ToString();
                            displayName = ((LuaTable)((LuaTable)description["Missions"])[1])["name"].ToString();
                        });

                        lua["make_flyable"] = new Action <string, string, LuaTable, string>((a, b, c, d) =>
                        {
                            if (displayName.Contains("_hornet"))
                            {
                                displayName = displayName.Split('_')[0];
                            }

                            if (!string.IsNullOrEmpty(moduleId) && autoupdateModules.Contains(moduleId) && moduleId != "FC3")
                            {
                                var module = new Module
                                {
                                    ModuleId = moduleId,
                                    DisplayName = displayName,
                                    LoadingImagePath = Path.Combine(folder, skinsPath, "ME", "loading-window.png"),
                                    MainMenuLogoPath = Path.Combine(folder, skinsPath, "ME", "MainMenulogo.png"),
                                    BaseFolderPath = folder,
                                    IconPath = Path.Combine(folder, skinsPath, "icon.png"),
                                    ViewportPrefix = moduleId.ToString().Replace(" ", "_").Replace("-", "_")
                                };
                                modules.Add(module);
                                Tracer.Info($"Found module {displayName}.");
                            }
                        });

                        try
                        {
                            lua.DoFile(entryPath);
                        }
                        catch (Exception e)
                        {
                            Tracer.Error(e);
                        }
                    }
                }

                return modules.ToArray();
            }));
        }