public void Start()
    {
        //Init LuaBinding class that demonstrates communication
        LuaBinding binding = new LuaBinding();

        //Init instance of Lua virtual machine (Note: Can only init ONCE)
        luaVirtualMachine = new Lua();
        //Tell Lua about the LuaBinding object to allow Lua to call C# functions
        luaVirtualMachine["luabinding"] = binding;

        //test luabinding test
        LuaBindingTest bindingTest = LuaBindingTest.SharedInstance();
        bindingTest.name = "name1";
        luaVirtualMachine["LuaBindingTest"] = bindingTest;
        //luaVirtualMachine[""] = ;

        //Debug.LogError("LuaManager: " + Application.persistentDataPath);

        //Run the code contained within the file
        #if UNITY_ANDROID
        luaVirtualMachine.DoFile("/sdcard/Download/"+LuaFileToLoad);
        #else
        luaVirtualMachine.DoFile(Application.streamingAssetsPath+"/"+LuaFileToLoad);
        #endif
        //Trigger binding in c# to call the bound Lua function

        binding.MessageToLua();
        TestStaticFunction();
    }
    public void Start()
    {
        //Init LuaBinding class that demonstrates communication
        LuaBinding binding = new LuaBinding();

        //Init instance of Lua virtual machine (Note: Can only init ONCE)
        luaVirtualMachine = new Lua();
        //Tell Lua about the LuaBinding object to allow Lua to call C# functions
        luaVirtualMachine["luabinding"] = binding;
        //Run the code contained within the file
        luaVirtualMachine.DoFile(Application.streamingAssetsPath+"/"+LuaFileToLoad);
        //Trigger binding in c# to call the bound Lua function
        binding.MessageToLua();
    }
Beispiel #3
0
        static void Main(string[] args)
        {
            // Create the Lua object.
            Lua lua = new Lua();
            dynamic E = lua.Environment;

            //E.TailCalls = Lua.UseDynamicTypes;
            E.DoThreads = true;

            // Expose these to Lua.
            lua.Register(typeof(ITest));
            lua.Register((Test)Foo);

            // Load and execute a Lua file.
            lua.DoFile("Tests.lua");
            
            // Keep the console window open.
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
Beispiel #4
0
	public LuaFunction boundMessageFunction; //Reference to bound Lua function set within Lua
	
	// Constructor
	public LuaAPI() {
		// create new instance of Lua
		lua = new Lua();
		
		// Initialize array.
		movementQueue = new Queue();
		
		// Get the UnityEngine reference
		lua.DoString("UnityEngine = luanet.UnityEngine");
		
		// get the boat and its controls
		boat = GameObject.FindGameObjectWithTag("TheBoat");
		shipControls = boat.GetComponent<ShipControls>();
		
		//Tell Lua about the LuaBinding object to allow Lua to call C# functions
		lua["luabinding"] = this;
		
		//Run the code contained within the file
		lua.DoFile(Application.streamingAssetsPath + "/" + drivers);
	}
Beispiel #5
0
        /// <inheritdoc />
        public void Load()
        {
            _logger.LogLoading("Loading quests...");

            using var lua = new Lua();

            lua["Jobs"] = Enum.GetValues(typeof(DefineJob.Job))
                          .Cast <DefineJob.Job>()
                          .ToDictionary(x => x.ToString(), x => (int)x);

            var quests = new ConcurrentDictionary <int, IQuestScript>();
            IEnumerable <string> questsDefinition = LoadQuestsDefinitions();
            IEnumerable <string> questFiles       = Directory.GetFiles(GameResourcesConstants.Paths.QuestsPath, "*.*", SearchOption.AllDirectories).Where(x => x != QuestDefinitionPath);

            foreach (string questFile in questFiles)
            {
                lua.DoFile(questFile);
            }

            foreach (var questName in questsDefinition)
            {
                var questTable = lua[questName] as LuaTable;

                if (!_defines.TryGetValue(questName, out int questId))
                {
                    if (questName.StartsWith(QuestScriptConstants.QuestPrefix) && !int.TryParse(questName.Replace(QuestScriptConstants.QuestPrefix, ""), out questId))
                    {
                        _logger.LogWarning($"Cannot find quest id for quest: '{questName}'.");
                        continue;
                    }
                }

                quests.TryAdd(questId, new QuestScript(questId, questName, questTable));
            }

            _logger.LogInformation($"-> {quests.Count} quests loaded.");
            _cache.Set(GameResourcesConstants.Quests, quests);
        }
Beispiel #6
0
                protected override void Run()
                {
                    LuaSystem luaSys = new LuaSystem(MainSession, MainSystem, StdOut, StdIn, StdErr);
                    Lua       l      = luaSys.Lua;

                    try
                    {
                        if (Argv.Count > 1)
                        {
                            NixPath newPath = OpenPath(Argv[1]);
                            string  file    = MainSystem.RootDrive.GetPathTo(newPath.ToString());
                            Debug.Log("File to load: " + newPath.ToString());
                            if (File.Exists(file))
                            {
                                string argStr = "arg={}\n";
                                argStr += "arg[0]=\"" + Argv[1].Replace("\\", "/") + "\"\n";
                                for (int i = 2; i < Argv.Count; i++)
                                {
                                    argStr += "arg[" + (i - 1) + "]=\"" + Argv[i] + "\"\n";
                                }
                                l.DoString(argStr);
                                l.DoFile(newPath.ToString());
                            }
                            else
                            {
                                StdOut.WriteLine("Unable to find file: " + Argv[1]);
                            }
                        }
                        else
                        {
                            // Do stdin stuff
                        }
                    }
                    catch (Exception exp)
                    {
                        StdOut.WriteLine("Exception executing Lua: " + exp.Message);
                    }
                }
Beispiel #7
0
        /// <summary>
        /// 初始化lua对象
        /// </summary>
        /// <param name="lua"></param>
        /// <returns></returns>
        public static void Initial(Lua lua)
        {
            //API查询遍历的类型列表
            //(可改写为从程序集检索,暂不修改)
            List<Type> searchTypes = new List<Type>
            {
                typeof(LuaApi),
                typeof(LuaEnv),
                typeof(XmlApi),
                typeof(TcpServer),
                typeof(Tools)
            };
            foreach(Type t in searchTypes)
            {
                //类型中查找所有静态方法
                MethodInfo[] mis = t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                foreach(MethodInfo mi in mis)
                {
                    //获取特性
                    LuaAPIFunctionAttribute lapiattr = mi.GetCustomAttribute<LuaAPIFunctionAttribute>();
                    if (lapiattr != null)
                    {
                        //获取自定义名称
                        string s = lapiattr.Name;
                        if (!string.IsNullOrEmpty(s))
                        {
                            lua.RegisterFunction(s, null, mi);
                        }
                        else
                        {
                            lua.RegisterFunction(mi.Name, null, mi);
                        }
                    }
                }
            }

            lua.DoFile(Common.AppDirectory + "lua/require/head.lua");
        }
Beispiel #8
0
                public Objective(string missionfile)
                {
                    missionFile = missionfile;
                    logEntries.Add(0);

                    if (!string.IsNullOrEmpty(missionFile))
                    {
                        luaScript = new Lua();
                        luaScript.DoFile(string.Format("Lua//Missions//{0}.lua", missionFile));

                        foreach (MethodInfo m in GetType().GetMethods())
                        {
                            luaScript.RegisterFunction(m.Name, this, m);
                        }
                    }

                    LuaFunction luaF = luaScript.GetFunction("OnInit");

                    if (luaF != null)
                    {
                        luaF.Call(this);
                    }
                }
Beispiel #9
0
        public bool Init()
        {
            var lua = new Lua();

            lua.RegisterFunction("InsertRecipe", this, typeof(ChangeMaterialMgr).GetMethod("InsertRecipe"));
            lua.DoFile("data\\ChangeMaterial.lua");
            LuaFunction f = lua.GetFunction("main");

            if (f != null)
            {
                var functionInfo = f.Call();
                if ((bool)functionInfo[0] == true)
                {
                    return(true);
                }
                else
                {
                    throw new ApplicationException(functionInfo[1].ToString());
                }
            }
            f.Dispose();
            return(false);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        public bool LoadLuaFile()
        {
            var lua = new Lua();

            lua.RegisterFunction("InsertTBL", this, typeof(Collection).GetMethod("InsertTBL"));
            lua.DoFile("data\\collection.lua");
            LuaFunction f = lua.GetFunction("main");

            if (f != null)
            {
                var functionInfo = f.Call();
                if ((bool)functionInfo[0] == true)
                {
                    return(true);
                }
                else
                {
                    throw new ApplicationException(functionInfo[1].ToString());
                }
            }
            f.Dispose();
            return(false);
        }
Beispiel #12
0
Datei: LUA.cs Projekt: vanehu/MM
 /// <summary>
 /// 获取函数
 /// </summary>
 /// <param name="file">文件名</param>
 /// <returns>返回函数</returns>
 public dynamic GetClass(string file)
 {
     if (string.IsNullOrEmpty(file))
     {
         Ex = "脚本文件名不能为空";
         return(null);
     }
     file = file.ToFullName(_Dir);
     if (!File.Exists(file))
     {
         Ex = "脚本不存在!请确认脚本:“" + file + "”是否存在。";
         return(null);
     }
     try
     {
         Lua Eng = new Lua();
         Eng.LoadCLRPackage();
         var dir = file.ToDir();
         Eng["SDK"] = new Helper.Indexer()
         {
             Dir = dir
         };
         Eng["Cache"]  = new Cache();
         Eng["Engine"] = new Indexer()
         {
             Dir = dir
         };
         var code = File.ReadAllText(file, Encoding.UTF8);
         Eng.DoFile(file);
         return(Eng.Pop());
     }
     catch (Exception ex)
     {
         Ex = ex.ToString();
     }
     return(null);
 }
Beispiel #13
0
        private void button2_Click(object sender, EventArgs e)
        {
#if USING_LUA
            using (Lua lua = new Lua())
            {
                // 初期化
                lua.LoadCLRPackage();

                //
                // 関数の登録
                //

                // Lua「writeLine("あー☆")」
                // ↓
                // C#「C onsole.WriteLine("あー☆")」
                lua.RegisterFunction("writeLine", typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));

                // Lua「random(0,100)」
                // ↓
                // C#「Util_Lua_KifuWarabe.Random(0,100)」
                lua.RegisterFunction("random", typeof(Uc_Main1).GetMethod("Random", new Type[] { typeof(double), typeof(double) }));

                // Luaファイル読込み
                lua.DoFile("./random.lua");

                // 実行
                lua.GetFunction("main").Call();

                var    scoreX = lua["score"];
                double score  = (double)scoreX;

                MessageBox.Show("scoreXの型=[" + scoreX.GetType().Name + "] score=[" + score + "]");

                //lua.Close(); // アプリが終了してしまう?
            }
#endif
        }
Beispiel #14
0
        public void OnLoad()
        {
            Enabled = true;

            _registeredEvents.Clear();
            _registeredCommands.Clear();

            Properties = new PluginProperties(Path.GetFileName(PluginFile), PluginManager.PluginDirectoryPath);
            Properties.Load();

            _lua = new Lua();
            _lua.LoadCLRPackage();

            _lua["properties"] = Properties;
            _lua["plugindir"]  = PluginManager.PluginDirectoryPath;

            _lua.DoString("package.path = package.path .. \";plugins/?.lua\"");

            RegisterTypes();
            RegisterFunctions();

            _lua.DoFile(PluginFile);

            LuaFunction onLoad = _lua.GetFunction("onLoad");

            if (onLoad != null)
            {
                try
                {
                    onLoad.Call();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Plugin {0} caused error: {1}", Path.GetFileName(PluginFile), ex.Message);
                }
            }
        }
Beispiel #15
0
 private void ExecuteScriptFile()
 {
     try
     {
         using (FileStream fs = File.Open(_scriptFilePath, FileMode.Open))
         {
         }
     }
     catch (Exception)
     {
         return;
     }
     finally
     {
         try
         {
             _lua.DoFile(_scriptFilePath);
         }
         catch (Exception ex)
         {
             Console.WriteLine($"Script error: {ex.Message}.");
         }
     }
 }
Beispiel #16
0
        public void TestBinaryLoadFile()
        {
            using (Lua lua = new Lua())
            {
                string file;
                lua.LoadCLRPackage();

                if (IntPtr.Size == 4)
                {
                    file = GetScriptsPath("test_32.luac");
                }
                else
                {
                    file = GetScriptsPath("test_64.luac");
                }

                lua.DoFile(file);

                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"];
                var      func    = (LuaFunction)lua["func"];
                object[] res     = func.Call(12, 34);
                int      x       = (int)(double)res[0];
                int      y       = (int)(double)res[1];


                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);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Loads the Lua scripts.
        /// </summary>
        /// <param name="reload">Is it a reload or not.</param>
        public void LoadScripts(bool reload = false)
        {
            lock (Lock)
            {
                if (reload)
                {
                    foreach (var func in _functions.RegisteredSchumix)
                    {
                        sIrcBase.SchumixRemoveHandler(func.Key, func.Value.Method);
                    }

                    foreach (var func in _functions.RegisteredIrc)
                    {
                        sIrcBase.IrcRemoveHandler(func.Key, func.Value);
                    }

                    _functions.Clean();
                }

                var di = new DirectoryInfo(_scriptPath);

                foreach (var file in di.GetFiles("*.lua").AsParallel())
                {
                    Log.Notice("LuaEngine", sLConsole.GetString("Loading Lua script: {0}"), file.Name);

                    try
                    {
                        _lua.DoFile(file.FullName);
                    }
                    catch (Exception e)
                    {
                        Log.Error("LuaEngine", sLConsole.GetString("Exception thrown while loading Lua script: {0} Error: {1}"), file.Name, e.Message);
                    }
                }
            }
        }
        private void LoadScripts()
        {
            /*
             * Do something involving reading a file to identify what functions I'm looking for
             * Load those functions into the sandbox, then pull them out and store them into the functions list
             * Somehow associate these with regexs
             */
            //Prep in case of a reload
            triggers.Clear();
            functions.Clear();

            //execute all lua files first
            DirectoryInfo dInfo = new DirectoryInfo(pathToScripts);

            FileInfo[] files = dInfo.GetFiles("*.lua");
            foreach (FileInfo file in files)
            {
                sandbox.DoFile(file.FullName);
            }
            //Get config files and identify the functions and their associated regexs
            files = dInfo.GetFiles("*.xml");
            XmlDocument doc = new XmlDocument();
            XmlNodeList nodes;

            foreach (FileInfo file in files)
            {
                doc.Load(file.FullName);
                nodes = doc.SelectNodes("/trigger");
                foreach (XmlNode node in nodes)
                {
                    triggers.Add(node.SelectSingleNode("\regex").Value);
                    Say(node.SelectSingleNode("\regex").Value);
                    functions.Add(sandbox[node.SelectSingleNode("\function").Value] as LuaFunction);
                }
            }
        }
        public static void Parse(string path)
        {
            //Clear from other data paths
            AvoidanceFamilies.Clear();

            lua = new Lua();
            lua.DoFile(path);

            LuaTable avoidanceFamilies = lua.GetTable("avoidanceFamily");

            foreach (LuaTable table in avoidanceFamilies)
            {
                string name     = "";
                int    numParam = -1;

                foreach (KeyValuePair <object, object> de in table.Values)
                {
                    switch (de.Key.ToString())
                    {
                    case "name":
                        name = de.Value.ToString();
                        break;

                    case "numParam":
                        string text = de.Value.ToString();
                        numParam = int.Parse(text);
                        break;
                    }
                }

                if (name.Length > 0)
                {
                    AvoidanceFamilies.Add(name);
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// 调用lua合并
        /// </summary>
        public void Merge()
        {
            int startTime = System.Environment.TickCount;
            Lua lua       = new Lua();

            lua.DoFile("core.lua");
            lua.RegisterFunction("msgbox", this, this.GetType().GetMethod("msgbox"));
            string      DestinationPath = GetDirectory(path[0]);
            LuaFunction luf2            = lua.GetFunction("AppendCSV");
            LuaFunction luf1            = lua.GetFunction("CreatCSV");

            //lua["Lenth"] = path.Length;
            for (int i = 0; i < path.ToArray().Length; i++)
            {
                updateProcessBar(i + 1);
                if (i == 0)
                {
                    luf1.Call(path[i], DestinationPath);
                }
                else
                {
                    //string filename = path[i];
                    // Thread.Sleep(5);//必须延迟10ms 否则出错!!!!!!!!!!!!!!

                    luf2.Call(path[i], DestinationPath);
                    // Thread.Sleep(5);
                    //Thread.Sleep(10);
                }
            }
            int endTime = System.Environment.TickCount;

            if (MessageBox.Show("finish,用时" + (endTime - startTime).ToString() + "ms" + "\r\n是否查看合并后的文件?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(DestinationPath);
            }
        }
Beispiel #21
0
        /// <summary>
        /// 获取注释生成文档
        /// </summary>
        /// <param name="path"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        private static string GetComments(string path, string encoding)
        {
            var lua = new Lua();

            lua.State.Encoding = Encoding.UTF8;
            lua["result"]      = "";
            lua.DoString("lines = {}");
            LuaTable t = (LuaTable)lua["lines"];

            int count = 1;

            if (!File.Exists(path))
            {
                Console.WriteLine($"file {path} not exist");
                return("");
            }
            foreach (var i in File.ReadAllLines(path, System.Text.Encoding.GetEncoding(encoding)))
            {
                t[count++] = i;
            }
            lua.DoFile("run.lua");

            return(lua["result"].ToString());
        }
Beispiel #22
0
        static void Main()
        {
            //Application.EnableVisualStyles();
            // Application.SetCompatibleTextRenderingDefault(false);
            // Application.Run(new Form1());
            // BufferTest.a();
            // System.Threading.Thread.Sleep(1000000);
            ConsumerContext.Init();
            ConsumerContext.lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            EchoClient.RunClientAsync().Wait();


            // System.Threading.Thread.CurrentThread.Suspend();
            System.Threading.Thread.Sleep(1000000);
            CodedInputStream             d;
            CodedOutputStream            b;
            ProtobufVarint32FrameDecoder c;

            // Console.WriteLine(Application.StartupPath);

            // Student student = new Student();

            Lua lua = new Lua();

            //lua.RegisterFunction("MethodA", student, student.GetType().GetMethod("MethodA"));
            lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            lua.DoFile("lua/LuaObj.lua");
            lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            // string path = "lua/com/senpure/io/ConsumerDecoder.lua";

            LuaFunction func = lua.GetFunction("hello");

            func.Call(new Student());

            // System.Threading.Thread.CurrentThread.Suspend();
        }
Beispiel #23
0
        private void LoadLuaFile(string strPath)
        {
            if (strPath == null || strPath == "")
            {
                netlua = new Lua();
                netlua.RegisterFunction("SetData", this, this.GetType().GetMethod("SetData"));
                netlua.RegisterFunction("GetData", this, this.GetType().GetMethod("GetData"));
                netlua.RegisterFunction("SetDataByIdx", this, this.GetType().GetMethod("SetDataByIdx"));
                netlua.DoFile(@"F:\2-lua\Lua_test_CS\Lua_test_CS\add.lua");

                //netlua.DoFile(strLuaFilePath);
                //timer1.Enabled = true;
            }
            else
            {
                netlua = new Lua();
                netlua.RegisterFunction("SetData", this, this.GetType().GetMethod("SetData"));
                netlua.RegisterFunction("GetData", this, this.GetType().GetMethod("GetData"));
                netlua.RegisterFunction("SetDataByIdx", this, this.GetType().GetMethod("SetDataByIdx"));

                netlua.DoFile(strPath);
                timer1.Enabled = true;
            }
        }
Beispiel #24
0
        public bool Init()
        {
            var lua = new Lua();

            lua.RegisterFunction("SetWorldServerID", this, typeof(WorldConfigMgr).GetMethod("SetWorldServerID"));
            lua.RegisterFunction("SetCharacterCount", this, typeof(WorldConfigMgr).GetMethod("SetCharacterCount"));
            lua.DoFile("data\\World.Config.lua");
            LuaFunction f = lua.GetFunction("main");

            if (f != null)
            {
                var functionInfo = f.Call();
                if ((bool)functionInfo[0] == true)
                {
                    return(true);
                }
                else
                {
                    throw new ApplicationException(functionInfo[1].ToString());
                }
            }
            f.Dispose();
            return(false);
        }
Beispiel #25
0
        public ControlSystem(Commander commander)
        {
            _commander = commander;

            var lua = new Lua();

            lua.NewTable("kbd");
            lua.DoFile("./Lua/controls.lua");

            var raw = lua.GetTableDict(lua.GetTable("kbd")) as Dictionary <object, object>;

            _kbdmap = new Dictionary <Keys, string>();
            foreach (var row in raw)
            {
                _kbdmap.Add(Enum.Parse <Keys>(row.Key.ToString()), row.Value.ToString());
            }

            lua.Dispose();

            // _kbdmap.Add(Keys.Q, "Exit");
            // _kbdmap.Add(Keys.Space, "Continue");
            // _kbdmap.Add(Keys.F, "Fullscreen");
            // _kbdmap.Add(Keys.D, "ToggleDebugConsole");
        }
        public override void Update(GameTime time, Entity entity)
        {
            this.time = time;
            base.Update(time, entity);

            var fn = (Lua_Function)entity.Get(Types.Lua_Function);

            try {
                fn.Function?.Call(entity, this);
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }

            if (fn.Auto_Reload)
            {
                var date_time = File.GetLastWriteTime(fn.File_Name);
                if (fn.Last_Date_Time == DateTime.MaxValue)
                {
                    fn.Last_Date_Time = date_time;
                }
                else
                {
                    if (date_time != fn.Last_Date_Time)
                    {
                        try
                        {
                            fn.Function = lua.DoFile(fn.File_Name)[0] as LuaFunction;
                        } catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                        fn.Last_Date_Time = date_time;
                    }
                }
            }
        }
        public ResourceReader(string path)
        {
            try
            {
                // Load profile
                json = JObject.Parse(File.ReadAllText(path));

                foreach (var obj in json)
                {
                    if (obj.Key == "Version")
                    {
                        Version = Version.Parse(obj.Value.ToObject <string>());
                    }
                    else if (obj.Key == "Target")
                    {
                        Target = obj.Value.ToObject <string>();
                    }
                    else if (obj.Key == "Platform")
                    {
                        Platform = obj.Value.ToObject <int>();
                        if (Platform != 32 && Platform != 64)
                        {
                            throw new Exception(string.Format("Invalid platform: {0}.", Platform));
                        }
                    }
                    else if (obj.Key == "Import")
                    {
                        LuaImport = obj.Value.ToObject <List <string> >();
                    }
                    else if (obj.Key == "Reset")
                    {
                        JObject reset_obj = JObject.Parse(obj.Value.ToString());
                        if (!reset_obj.ContainsKey("Parameters"))
                        {
                            throw new Exception("Parameters for reset function not defined.");
                        }
                        reset.Parameters = reset_obj["Parameters"].ToObject <List <string> >();
                    }
                    else
                    {
                        ResourceObject resource = new ResourceObject();
                        foreach (var attr in JObject.Parse(obj.Value.ToString()))
                        {
                            if (attr.Key == "Name")
                            {
                                resource.Name = attr.Value.ToObject <string>();
                            }
                            else if (attr.Key == "Description")
                            {
                                resource.Description = attr.Value.ToObject <string>();
                            }
                            else if (attr.Key == "DataType")
                            {
                                resource.DataType = attr.Value.ToObject <string>();
                            }
                            else if (attr.Key == "Type")
                            {
                                resource.Type = attr.Value.ToObject <string>();
                            }
                            else if (attr.Key == "Address")
                            {
                                resource.Address = attr.Value.ToObject <List <string> >();
                            }
                            else if (attr.Key == "Display")
                            {
                                resource.Display = attr.Value.ToObject <Dictionary <string, string> >();
                            }
                            else if (attr.Key == "Parameters")
                            {
                                resource.Parameters = attr.Value.ToObject <List <string> >();
                            }
                            else
                            {
                                throw new Exception(string.Format("Unknown key defined: {0}.\nIn variable: {1}.", attr.Key, obj.Key));
                            }
                        }
                        if (resource.Name == null)
                        {
                            throw new Exception(string.Format("\"Name\" not defined.\nIn variable: {0}.", obj.Key));
                        }
                        else if (resource.DataType == null)
                        {
                            throw new Exception(string.Format("\"DataType\" not defined.\nIn variable: {0}.", obj.Key));
                        }
                        else if (resource.Type == null)
                        {
                            throw new Exception(string.Format("\"Type\" not defined.\nIn variable: {0}.", obj.Key));
                        }
                        else if (resource.Type != "Static" && resource.Type != "Counter" && resource.Type != "Custom")
                        {
                            throw new Exception(string.Format("Unknown value type defined: {0}.\nIn variable: {1}.", resource.Type, obj.Key));
                        }
                        else if ((resource.Type == "Static" || resource.Type == "Counter") && resource.Address == null)
                        {
                            throw new Exception(string.Format("\"Address\" not defined.\nIn variable: {0}.", obj.Key));
                        }
                        else if (resource.Type == "Custom" && resource.Parameters == null)
                        {
                            throw new Exception(string.Format("Parameters for custom function not defined.\nIn variable: {0}.", obj.Key));
                        }
                        else
                        {
                            ResourceList.Add(obj.Key, resource);
                            ResourceValueList.Add(obj.Key, DataConverter.GetDataType(resource.DataType));
                            PrintList.Add(obj.Key, resource.Type == "Static" ? DataConverter.GetDataType(resource.DataType) : 0);
                        }
                    }
                }

                if (Version == null)
                {
                    throw new Exception("\"Version\" not defined.");
                }
                else if (Target == null)
                {
                    throw new Exception("\"Target\" not defined.");
                }
                else if (Platform == 0)
                {
                    throw new Exception("\"Platform\" not defined.");
                }
                else if (LuaImport == null)
                {
                    throw new Exception("\"Import\" not defined.");
                }
                else
                {
                    // Do nothing
                }

                // Load Lua functions
                foreach (string file in LuaImport)
                {
                    state.DoFile(Path.Combine(Directory.GetParent(path).FullName, file));
                }

                reset.Function = state["Reset"] as LuaFunction;
                if (reset.Parameters != null && reset.Function == null)
                {
                    throw new Exception("Function Reset not found.");
                }

                foreach (var obj in ResourceList)
                {
                    if (obj.Value.Type == "Counter" || obj.Value.Type == "Custom")
                    {
                        if (!(state[obj.Key] is LuaFunction function))
                        {
                            throw new Exception(string.Format("Function \"{0}\" not found.", obj.Key));
                        }
                        FunctionList.Add(obj.Key, function);
                    }
                }

                Okay = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Parse Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            Encode        = false;
            Console.Title = "PWLuaOOG 0.3b [by JonMagon]";

            Console.WriteLine("PWLuaOOG 0.3b [by JonMagon]");
            Console.WriteLine("");

            lua["Console"]        = new LuaConsole();
            lua["ReceivedPacket"] = new ReceivedPacket();
            lua["SendPacket"]     = new SendPacket();
            lua["Protocol"]       = new Protocol();
            lua["Crypt"]          = new Crypt();
            lua["Math"]           = new Math();

            // Очень криво работают потоки
            //Threads threads = new Threads();
            //lua.RegisterFunction("Thread", threads, threads.GetType().GetMethod("Thread"));

            SendPacket.Data = new List <byte>();

            Client                 = new NetClient();
            Client.OnConnected    += client_OnConnected;
            Client.OnDisconnected += Client_OnDisconnected;
            Client.OnReceived     += client_OnReceived;

            try
            {
                lua.DoFile(@".\scripts\main.lua");

                if (lua["debug_mode"] != null)
                {
                    debug_mode = true;
                }

                SendPacket.debug_mode = debug_mode;

                Functions.Add(FunctionType.Main, (LuaFunction)lua["Main"]);
                Functions.Add(FunctionType.Connected, (LuaFunction)lua["Connected"]);
                Functions.Add(FunctionType.Disconnected, (LuaFunction)lua["Disconnected"]);
                Functions.Add(FunctionType.Received, (LuaFunction)lua["Received"]);
                Functions.Add(FunctionType.ReceivedSubPacket, (LuaFunction)lua["ReceivedSubPacket"]);

                if (Functions[FunctionType.Main] == null)
                {
                    throw new Exception("Ошибка: не найдена функция инициализации Main");
                }

                if (Functions[FunctionType.Connected] == null)
                {
                    Console.WriteLine("Предупреждение: не найдена функция Connected()");
                }

                if (Functions[FunctionType.Disconnected] == null)
                {
                    Console.WriteLine("Предупреждение: не найдена функция Disconnected()");
                }

                if (Functions[FunctionType.Received] == null)
                {
                    Console.WriteLine("Предупреждение: не найдена функция Received(opcode, length)");
                }

                if (Functions[FunctionType.ReceivedSubPacket] == null)
                {
                    Console.WriteLine("Предупреждение: не найдена функция ReceivedSubPacket(opcode, length)");
                }

                Functions[FunctionType.Main].Call();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                return;
            }
        }
Beispiel #29
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();
        }
Beispiel #30
0
        public DataLoader()
        {
            lua["package.path"] = Settings.FactorioPath + @"\data\base\?";
            lua["package.path"] = lua["package.path"] + ";" + Settings.FactorioPath + @"\data\base\?.lua";
            lua["package.path"] = lua["package.path"] + ";" + Settings.FactorioPath + @"\data\core\?";
            lua["package.path"] = lua["package.path"] + ";" + Settings.FactorioPath + @"\data\core\?.lua";
            lua["package.path"] = lua["package.path"] + ";" + Settings.FactorioPath + @"\data\core\lualib\?";
            lua["package.path"] = lua["package.path"] + ";" + Settings.FactorioPath + @"\data\core\lualib\?.lua";
            string luascript = (@"
                    require ('util')

                    function log(...)
                    end

                    serpent = {}
                    serpent.block = function(n) return '' end
                    
                    settings = {}    
                    settings.startup = {}
                    defines = {}
                    defines.difficulty_settings = {}
                    defines.difficulty_settings.recipe_difficulty = {}
                    defines.difficulty_settings.technology_difficulty = {}
                    defines.difficulty_settings.recipe_difficulty.normal = 1
                    defines.difficulty_settings.technology_difficulty.normal = 1
                    defines.direction = {}
                    defines.direction.north = 1
                    defines.direction.east = 2
                    defines.direction.south = 3
                    defines.direction.west = 4
                    require('data')
                    require('data-updates')
                ");

            lua.DoFile(Settings.FactorioPath + @"\data\core\lualib\dataloader.lua");
            lua.DoFile(Settings.FactorioPath + @"\data\core\data.lua");
            lua.DoString(luascript);

            lua.DoString(@"
                        function electrolyserpictures() end
                        data.raw['item-subgroup']['bob-greenhouse-items'] = {}
                        data.raw['item-subgroup']['bob-greenhouse-items'].group = 'bob-intermediate-products'
                        mods = {}
                        ");

            LoadMods();

            LuaTable rawRecipes            = lua.GetTable("data.raw")["recipe"] as LuaTable;
            LuaTable rawFluids             = lua.GetTable("data.raw")["fluid"] as LuaTable;
            LuaTable rawItems              = lua.GetTable("data.raw")["item"] as LuaTable;
            LuaTable rawAssemblingMachines = lua.GetTable("data.raw")["assembling-machine"] as LuaTable;
            LuaTable rawFurnaces           = lua.GetTable("data.raw")["furnace"] as LuaTable;
            LuaTable rawMiningDrills       = lua.GetTable("data.raw")["mining-drill"] as LuaTable;
            LuaTable rawResources          = lua.GetTable("data.raw")["resource"] as LuaTable;
            LuaTable rawModules            = lua.GetTable("data.raw")["module"] as LuaTable;

            var fluidEnumerator = rawFluids.GetEnumerator();

            while (fluidEnumerator.MoveNext())
            {
                AddIconToCollection(fluidEnumerator.Value as LuaTable);
                Fluid newFluid = InterpretFluid(fluidEnumerator.Key as string, fluidEnumerator.Value as LuaTable);
                if (newFluid != null)
                {
                    Data.AddFluid(newFluid.name, newFluid);
                }
            }

            var itemEnumerator = rawItems.GetEnumerator();

            while (itemEnumerator.MoveNext())
            {
                AddIconToCollection(itemEnumerator.Value as LuaTable);
                Item newItem = InterpretItem(itemEnumerator.Key as string, itemEnumerator.Value as LuaTable);
                if (newItem != null)
                {
                    Data.AddItem(newItem.name, newItem);
                    if (newItem.category != "" && !Data.ItemCategories.Contains(newItem.category))
                    {
                        Data.ItemCategories.Add(newItem.category);
                    }
                    if (newItem.subgroup != "" && !Data.ItemSubgroups.Contains(newItem.subgroup))
                    {
                        Data.ItemSubgroups.Add(newItem.subgroup);
                    }
                }
            }

            var recipeEnumerator = rawRecipes.GetEnumerator();

            while (recipeEnumerator.MoveNext())
            {
                AddIconToCollection(recipeEnumerator.Value as LuaTable);
                Recipe newRecipe = InterpretRecipe(recipeEnumerator.Key as string, recipeEnumerator.Value as LuaTable);
                if (newRecipe != null)
                {
                    Data.AddRecipe(newRecipe);
                    if (newRecipe.category != "" && !Data.RecipeCategories.Contains(newRecipe.category))
                    {
                        Data.RecipeCategories.Add(newRecipe.category);
                    }
                    if (newRecipe.subgroup != "" && !Data.RecipeSubgroups.Contains(newRecipe.subgroup))
                    {
                        Data.RecipeSubgroups.Add(newRecipe.subgroup);
                    }
                }
            }

            Data.Locale.Count();
        }
Beispiel #31
0
            public bool Start()
            {
                lock (FLock)
                {
                    FLua = CreateLuaVM();

                    FLua.DoFile(FBotDesc.Script);

                    FLua.NewTable("BotEvent");
                    FLuaEvent = FLua.GetTable("BotEvent");
                    FLuaEventHandler = FLua.GetFunction("OnEvent");

                    BotEvent_Start startEvent = new BotEvent_Start(FBotId);

                    EmmitBotEvent(startEvent);

                    return startEvent.ret_val;
                }
            }
 public void ExecuteFile(string luaFileName)
 {
     Logger.Info("开始执行脚本:" + luaFileName);
     _luaVM.DoFile(luaFileName);
 }
Beispiel #33
0
 public MoneyLib()
 {
     State = new Lua();
     State.DoFile("./MoneyLib.lua");
 }
Beispiel #34
0
 void AssertFile(string path)
 {
     lua.DoFile(path);
 }
Beispiel #35
0
        public int RunConfig(string CurrentConfigBoxName, string CSVFilePath)
        {
            //////////////////////////////////////////////////////////////////
            // FILTRAGE DES ERREURS //////////////////////////////////////////
            //////////////////////////////////////////////////////////////////
            if (CurrentConfigBoxName.Length == 0)
            {
                MessageBox.Show("Aucune Config n'est sélèctionnée");
                return(-1);
            }

            if (CSVFilePath.Length == 0)
            {
                MessageBox.Show("Aucun fichier CSV n'est défini");
                return(-1);
            }

            if (System.IO.File.Exists(CSVFilePath) == false)
            {
                MessageBox.Show("Le fichier CSV n'existe pas sous ce chemin");
                return(-1);
            }

            //////////////////////////////////////////////////////////////////
            // INTIALISATION DU PROCESSUS ////////////////////////////////////
            //////////////////////////////////////////////////////////////////

            // ERROR VARIABLE
            ErrorProcessus     = false;
            ErrorProcessString = "";

            // DELETE LOG FILE
            DeleteLogFile();

            // CLEAR CONSOLE BOX
            // on efface la consolebox dans la mainform dnas la fonction private void button2_Click(object sender, EventArgs e)

            int result = InitLuaFunctions(); // on init les fontions qui vont etre utilisées dans lua

            string appPath = Path.GetDirectoryName(Application.ExecutablePath);

            string luaScriptFile = appPath + "\\scripts\\" + CurrentConfigBoxName;

            try
            {
                luaInterpret.DoFile(luaScriptFile);
            }
            catch (Exception e)
            {
                AddToLogFile(e.ToString());

                // Make asynchronous call to main form
                // to inform it that thread finished
                m_form.Invoke(m_form.m_DelegateThreadFinished, null);
                StopProcess(e.ToString());
                return(-1);
            }

            try
            {
                luaInterpret.DoString("Init();");
            }
            catch (Exception e)
            {
                AddToLogFile(e.ToString());

                // Make asynchronous call to main form
                // to inform it that thread finished
                m_form.Invoke(m_form.m_DelegateThreadFinished, null);
                StopProcess(e.ToString());
                return(-1);
            }

            //////////////////////////////////////////////////////////////////
            // TAILLE DU FICHIER CSV /////////////////////////////////////////
            //////////////////////////////////////////////////////////////////
            long FileSize = 0;

            try
            {
                FileInfo f = new FileInfo(CSVFilePath);
                FileSize = f.Length;
            }
            catch (Exception e)
            {
                AddToLogFile(e.ToString());

                // Make asynchronous call to main form
                // to inform it that thread finished
                m_form.Invoke(m_form.m_DelegateThreadFinished, null);
                StopProcess(e.ToString());
                return(-1);
            }

            // get extention
            string ext = Path.GetExtension(CSVFilePath);

            if (ext == "csv")
            {
                //////////////////////////////////////////////////////////////////
                // LECTURE DU FICHIER CSV ////////////////////////////////////////
                //////////////////////////////////////////////////////////////////

                // On va ouvir le fichier CSV
                currentLineIndex = 0;
                string line;
                long   sizeLine = 0;

                System.IO.StreamReader file = null;

                try
                {
                    // Read the file and display it line by line.
                    file = new System.IO.StreamReader(CSVFilePath, System.Text.Encoding.Default);
                }
                catch (Exception e)
                {
                    AddToLogFile(e.ToString());

                    // Make asynchronous call to main form
                    // to inform it that thread finished
                    m_form.Invoke(m_form.m_DelegateThreadFinished, null);
                    StopProcess(e.ToString());
                    return(-1);
                }

                while ((line = file.ReadLine()) != null)
                {
                    // check if thread is cancelled
                    if (m_EventStop.WaitOne(0, true))
                    {
                        // clean-up operations may be placed here
                        // ...

                        file.Close();

                        // inform main thread that this thread stopped
                        m_EventStopped.Set();

                        return(-1);
                    }

                    if (ErrorProcessus == true)
                    {
                        MessageBox.Show(ErrorProcessString, "Processus stoppé");
                        break;
                    }

                    // Set CurrentLine
                    result = ParseCSVLineToLuaTable(currentLineName, line);

                    // Exec Function for Each Row
                    ExecFonctionForEachLine();

                    // Set LastLine
                    result = ParseCSVLineToLuaTable(lastLineName, line);

                    // MAJ DE LA PROGRESSBAR
                    sizeLine += (long)line.Length;
                    int percent = (int)((sizeLine * 100) / FileSize);
                    // Make asynchronous call to main form
                    // to set progressbar
                    m_form.Invoke(m_form.m_DelegateSetProgressValue, new Object[] { percent });

                    currentLineIndex++;
                }

                // Exec Function for End File
                ExecFonctionForEndFile();

                file.Close();
            }
            else if (ext == "xml")
            {
                //////////////////////////////////////////////////////////////////
                // LECTURE DU FICHIER XML de type Office SpreadSheet /////////////
                //////////////////////////////////////////////////////////////////

                // On va ouvir le fichier XML
                currentLineIndex = 0;
                string line     = "";
                long   sizeLine = 0;

                System.IO.StreamReader file = null;

                XmlReader xmlReader;

                try
                {
                    xmlReader = XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
                }
                catch (Exception e)
                {
                    AddToLogFile(e.ToString());

                    // Make asynchronous call to main form
                    // to inform it that thread finished
                    m_form.Invoke(m_form.m_DelegateThreadFinished, null);
                    StopProcess(e.ToString());
                    return(-1);
                }

                while (xmlReader.Read())
                {
                    // check if thread is cancelled
                    if (m_EventStop.WaitOne(0, true))
                    {
                        xmlReader.Close();

                        // inform main thread that this thread stopped
                        m_EventStopped.Set();

                        return(-1);
                    }

                    if (ErrorProcessus == true)
                    {
                        MessageBox.Show(ErrorProcessString, "Processus stoppé");
                        break;
                    }

                    if (xmlReader.NodeType == XmlNodeType.Element)
                    {
                        if (xmlReader.Name == "Workbook")
                        {
                            if (xmlReader.GetAttribute("xmlns") != "urn:schemas-microsoft-com:office:spreadsheet")
                            {
                                break;                // pas le bon format de fichier
                            }
                        }

                        if (xmlReader.Name == "Row")
                        {
                        }
                    }

                    // Set CurrentLine
                    result = ParseCSVLineToLuaTable(currentLineName, line);

                    // Exec Function for Each Row
                    ExecFonctionForEachLine();

                    // Set LastLine
                    result = ParseCSVLineToLuaTable(lastLineName, line);

                    // MAJ DE LA PROGRESSBAR
                    sizeLine += (long)line.Length;
                    int percent = (int)((sizeLine * 100) / FileSize);
                    // Make asynchronous call to main form
                    // to set progressbar
                    m_form.Invoke(m_form.m_DelegateSetProgressValue, new Object[] { percent });

                    currentLineIndex++;
                }

                // Exec Function for End File
                ExecFonctionForEndFile();

                file.Close();
            }

            m_form.Invoke(m_form.m_DelegateSetProgressValue, new Object[] { 100 });

            // Make asynchronous call to main form
            // to inform it that thread finished
            m_form.Invoke(m_form.m_DelegateThreadFinished, null);

            return(0);
        }
Beispiel #36
0
        /*
         * Sample test script that shows some of the capabilities of
         * LuaInterface
         */
        public static void Main()
        {
            Console.WriteLine("Starting interpreter...");
            var l = new Lua();

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

            // Pause so we can connect with the debugger
            // Thread.Sleep(30000);
            l.RegisterFunction("func1", null, typeof(TestLuaInterface).GetMethod("func"));
            vals1 = l.GetFunction("func1").Call(2, 3);
            Console.WriteLine("Returned: " + vals1[0]);
            TestLuaInterface obj = new TestLuaInterface();
            Console.WriteLine("Registering a C# instance method and calling it from Lua...");
            l.RegisterFunction("func2", obj, typeof(TestLuaInterface).GetMethod("funcInstance"));
            vals1 = l.GetFunction("func2").Call(2, 3);
            Console.WriteLine("Returned: " + vals1[0]);

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

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

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

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

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

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

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

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

            Console.WriteLine("Test method overloads...");
            obj.TestMethodOverloads();

            Console.WriteLine("Test accessing private method...");
            obj.TestPrivateMethod();

            Console.WriteLine("Test event exceptions...");
            obj.TestEventException();

            Console.WriteLine("Test chunk overload exception...");
            obj.TestExceptionWithChunkOverload();

            Console.WriteLine("Test generics...");
            obj.TestGenerics();

            Console.WriteLine("Test threading...");
            obj.TestThreading();

            Console.WriteLine("Test memory leakage...");
            obj.TestDispose();

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }