Exemplo n.º 1
0
        public void OnActivate()
        {
            // Create the lua state
            luastate = new Lua();

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

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

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

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

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

            // Load lua files
            if (!Directory.Exists("lua")) Directory.CreateDirectory("lua");
            foreach (string name in Directory.GetFiles("lua"))
                luastate.DoFile("lua/" + name);
        }
Exemplo n.º 2
0
        public Engine()
        {
            Lua = new LuaInterface.Lua();
            Lua.NewTable("Client");
            Lua.RegisterFunction("Client.ChangeState", this, this.GetType().GetMethod("ChangeClientState"));
            Lua.NewTable("NS");
            Lua.NewTable("NS.Minor");

            Lua.RegisterFunction("NS.Run", this, this.GetType().GetMethod("MethodName"));
            Lua.RegisterFunction("Print", this, this.GetType().GetMethod("Print"));
            Lua.RegisterFunction("print", this, this.GetType().GetMethod("Print"));
        }
Exemplo n.º 3
0
        public static void Enumeration <T>(Lua lua)
        {
            #region Sanity checks
            if (lua.IsNull())
            {
                throw new ArgumentNullException("lua");
            }
            #endregion

            var type = typeof(T);

            if (!type.IsEnum)
            {
                throw new ArgumentException("The type must be an enumeration!");
            }

            string[] names  = Enum.GetNames(type);
            var      values = (T[])Enum.GetValues(type);
            lua.NewTable(type.Name);

            for (int i = 0; i < names.Length; i++)
            {
                string path = type.Name + "." + names[i];
                lua[path] = values[i];
            }
        }
Exemplo n.º 4
0
        public static LuaTable CreateTable(this LuaInterface.Lua lua, string tableName)
        {
            if (string.IsNullOrEmpty(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }

            lua.NewTable(tableName);
            return(lua.GetTable(tableName));
        }
Exemplo n.º 5
0
        //[STAThread]
        private static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                // For attaching from the debugger
                // Thread.Sleep(20000);

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

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

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

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

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

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

                        // wait for keypress if there is an error
                        Console.ReadKey();
                        // steffenj: END error message improved
                    }
                }
            }
            else
            {
                Console.WriteLine("LuaRunner -- runs Lua scripts with CLR access");
                Console.WriteLine("Usage: luarunner <script.lua> [{<arg>}]");
            }
        }
Exemplo n.º 6
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>}]");
            }
        }
Exemplo n.º 7
0
        public void OnActivate(params object[] args)
        {
            // Create the lua state
            luastate = new Lua();

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

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

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

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

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

            // Load lua files
            if (!Directory.Exists("lua")) Directory.CreateDirectory("lua");
            foreach (string name in Directory.GetFiles("lua"))
                luastate.DoFile(name);
        }
Exemplo n.º 8
0
		public static LuaTable ToLuaTable(Lua lua, object obj)
		{
			var table = lua.NewTable();

			var type = obj.GetType();

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

			return table;
		}
Exemplo n.º 9
0
        private LuaTable ToLuaTable(MemoryTable table)
        {
            String name = "memory_table_" + new Random().Next().ToString();

            lua.NewTable(name);
            LuaTable newTable = lua.GetTable(name);

            foreach (KeyValuePair <String, Object> obj in newTable)
            {
                if (obj.GetType() == typeof(MemoryTable))
                {
                    newTable[obj.Key] = ToLuaTable((MemoryTable)obj.Value);
                }
                else
                {
                    newTable[obj.Key] = obj.Value;
                }
            }
            return(newTable);
        }
Exemplo n.º 10
0
        /*
         * Sample test script that shows some of the capabilities of
         * LuaInterface
         */
        public static void Main()
        {
            Console.WriteLine("Starting interpreter...");
            Lua l=new Lua();

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

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

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

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

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

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

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

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

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

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

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

            Console.WriteLine("Test event exceptions...");
            obj.TestEventException();
        }
Exemplo n.º 11
0
 public static LuaTable CreateTable(this LuaInterface.Lua lua)
 {
     lua.NewTable("my");
     return(lua.GetTable("my"));
 }
Exemplo n.º 12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public LuaTable CreateTable(string name)
 {
     _lua.NewTable(name);
     return(_lua.GetTable(name));
 }
Exemplo n.º 13
0
 public static void Register(Lua L)
 {
     L.NewTable("utils");
     LuaRegistrationHelper.TaggedStaticMethods(L,typeof(MyClass));
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hellow Lua");


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

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

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


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


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

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

            #endregion


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

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

            #endregion
            Console.ReadKey();
            lua.Dispose();
        }