/// <summary> /// Registers all public instance methods in an object tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions /// </summary> /// <param name="lua">The Lua VM to add the methods to</param> /// <param name="o">The object to get the methods from</param> public static void TaggedInstanceMethods(LuaInterface lua, object o) { #region Sanity checks if (lua == null) { throw new ArgumentNullException("lua"); } if (o == null) { throw new ArgumentNullException("o"); } #endregion foreach (MethodInfo method in o.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)) { foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), true)) { if (string.IsNullOrEmpty(attribute.Name)) { lua.RegisterFunction(method.Name, o, method); // CLR name } else { lua.RegisterFunction(attribute.Name, o, method); // Custom name } } } }
public static void Enumeration <T>(LuaInterface lua) { #region Sanity checks if (lua == null) { throw new ArgumentNullException("lua"); } #endregion Type type = typeof(T); if (!type.IsEnum) { throw new ArgumentException("The type must be an enumeration!"); } string[] names = Enum.GetNames(type); T[] 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]; } }
/// <summary> /// Registers all public static methods in a class tagged with <see cref="LuaGlobalAttribute"/> as Lua global functions /// </summary> /// <param name="lua">The Lua VM to add the methods to</param> /// <param name="type">The class type to get the methods from</param> public static void TaggedStaticMethods(LuaInterface lua, Type type) { #region Sanity checks if (lua == null) { throw new ArgumentNullException("lua"); } if (type == null) { throw new ArgumentNullException("type"); } if (!type.IsClass) { throw new ArgumentException("The type must be a class!", "type"); } #endregion foreach (MethodInfo method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)) { foreach (LuaGlobalAttribute attribute in method.GetCustomAttributes(typeof(LuaGlobalAttribute), false)) { if (string.IsNullOrEmpty(attribute.Name)) { lua.RegisterFunction(method.Name, null, method); // CLR name } else { lua.RegisterFunction(attribute.Name, null, method); // Custom name } } } }
/// <summary> /// Set a LuaInterface to use with this LuaState. Throws an exception if there /// already is one. /// </summary> /// <param name="li"></param> public void SetInterface(LuaInterface li) { if (_interface == null) { _interface = li; } else { throw new Exception("A LuaInterface is already attached to this LuaState"); } }
public virtual void Dispose(bool disposeManagedResources) { if (!_Disposed) { if (disposeManagedResources) { if (_Reference != 0) _Interpreter.dispose(_Reference); } _Interpreter = null; _Disposed = true; } }
public virtual void Dispose(bool disposeManagedResources) { if (!_Disposed) { if (disposeManagedResources) { if (_Reference != 0) { _Interpreter.dispose(_Reference); } } _Interpreter = null; _Disposed = true; } }
public ObjectTranslator(LuaInterface interpreter, SharpLua.Lua.LuaState luaState) { this.interpreter = interpreter; typeChecker = new CheckType(this); metaFunctions = new MetaFunctions(this); importTypeFunction = new SharpLua.Lua.lua_CFunction(this.importType); loadAssemblyFunction = new SharpLua.Lua.lua_CFunction(this.loadAssembly); registerTableFunction = new SharpLua.Lua.lua_CFunction(this.registerTable); unregisterTableFunction = new SharpLua.Lua.lua_CFunction(this.unregisterTable); getMethodSigFunction = new SharpLua.Lua.lua_CFunction(this.getMethodSignature); getConstructorSigFunction = new SharpLua.Lua.lua_CFunction(this.getConstructorSignature); ctypeFunction = new SharpLua.Lua.lua_CFunction(this.ctype); enumFromIntFunction = new SharpLua.Lua.lua_CFunction(this.enumFromInt); createLuaObjectList(luaState); createIndexingMetaFunction(luaState); createBaseClassMetatable(luaState); createClassMetatable(luaState); createFunctionMetatable(luaState); setGlobalFunctions(luaState); }
//internal int _Reference; //private Lua _Interpreter; public LuaUserData(int reference, LuaInterface interpreter) { _Reference = reference; _Interpreter = interpreter; }
public static void SetLua(Lua.LuaState lua) { _interface = lua.Interface; }
public static void SetLua(LuaInterface i) { _interface = i; }
public LuaFunction(SharpLua.Lua.lua_CFunction function, LuaInterface interpreter) { _Reference = 0; this.function = function; _Interpreter = interpreter; }
/// <summary> /// Set a LuaInterface to use with this LuaState. Throws an exception if there /// already is one. /// </summary> /// <param name="li"></param> public void SetInterface(LuaInterface li) { if (_interface == null) _interface = li; else throw new Exception("A LuaInterface is already attached to this LuaState"); }
//internal int _Reference; //private Lua _Interpreter; public LuaTable(int reference, LuaInterface interpreter) { _Reference = reference; _Interpreter = interpreter; }
public LuaState(LuaInterface i) { _interface = i; }
/// <summary> /// Compile the file filename for device and place user and completionCode into the resulting gwc file /// </summary> /// <param name="filename">Filename of the gwz file with path.</param> /// <param name="device">Name of the device for which the resulting gwc is compiled.</param> /// <param name="username">Username, which is wrote to gwc file and later used as Player.Name.</param> /// <param name="userid">User ID from Groundspeak, which is wrote to gwc file.</param> /// <param name="completionCode">CompletionCode, which is wrote to gwc file and later used as Player.CompletionCode.</param> /// <returns>Memory stream with the gwc file.</returns> public MemoryStream Compile(string filename, DeviceType device, string username = "", long userid = 0, string completionCode = "") { // Create object for player specific code Player player = new Player(device); // Create parser with filename Parser parser = new Parser(filename); // Open gwz for later use ZipFile zip = new ZipFile(parser.FilenameGwz); // Create object for all data belonging to the cartridge Cartridge cartridge = new Cartridge (); // Check, if the gwz file has the right format if (!parser.CheckGWZ(zip, cartridge)) { // Error in parsing gwz file throw new InvalidOperationException(String.Format("Line {0}, Column {1}: {2}", parser.Errors[0].Line, parser.Errors[0].Column, parser.Errors[0].Message)); } // Create LuaInterface LuaInterface lua = new LuaInterface(); string luaCode; // Create new Lua file with player specific characters and all other stuff luaCode = parser.UpdateLua(zip,player); // Only for debug reasons // saveLuaCode(luaCode); // Now we have a string with the Lua code, which have the right coding // So go on and compile the Lua code // LoadString of Lua code = compile Lua code LuaFunction func = lua.LoadString(luaCode, cartridge.Name); // Dump Lua code to memory stream, so we could later save it to gwc file MemoryStream luaBinary = new MemoryStream(); dumpCode(lua.LuaState,luaBinary); // Create memory stream to write gwc file MemoryStream stream = new MemoryStream(); BinaryWriter output = new BinaryWriter(stream); long savePosition; // Write gwc signature output.Write(new byte[7] { 0x02, 0x0a, 0x43, 0x41, 0x52, 0x54, 0x00 }); // Write number of images output.Write(getShort((short)(cartridge.MediaList.Count+1))); // Write media table for (int i = 0; i <= cartridge.MediaList.Count; i++) { output.Write(getShort((short)i)); output.Write(getInt((int)0)); } // Write size of header output.Write(getInt(0)); // Save position, where header starts long startHeader = output.BaseStream.Position; // Write header // Write position output.Write(getDouble((float) cartridge.Latitude)); output.Write(getDouble((float) cartridge.Longitude)); output.Write(getDouble((float) cartridge.Altitude)); // Write creation date // TODO: Replace with creation date string date = cartridge.CreateDate; output.Write(getLong(0)); // Write media index short splash = -1; for (int i = 0; i < cartridge.MediaList.Count; i++) if (cartridge.Splash != null && cartridge.Splash.Equals(cartridge.MediaList[i].Variable)) splash = (short)(i + 1); output.Write(getShort(splash)); // Write icon index short icon = -1; for (int i = 0; i < cartridge.MediaList.Count; i++) if (cartridge.Icon != null && cartridge.Icon.Equals(cartridge.MediaList[i].Variable)) icon = (short)(i + 1); output.Write(getShort(icon)); // Write cartridge type output.Write(getAscii(player.ConvertGWCString(cartridge.Activity))); // Write player data output.Write(getAscii(player.ConvertGWCString(username))); output.Write(getLong(userid)); // Write cartridge relevant information output.Write(getAscii(player.ConvertGWCString(cartridge.Name))); output.Write(getAscii(cartridge.Id)); output.Write(getAscii(player.ConvertGWCString(cartridge.Description))); output.Write(getAscii(player.ConvertGWCString(cartridge.StartingLocationDescription))); output.Write(getAscii(cartridge.Version)); output.Write(getAscii(player.ConvertGWCString(cartridge.Author))); output.Write(getAscii(player.ConvertGWCString(cartridge.Company))); output.Write(getAscii(player.ConvertGWCString(cartridge.TargetDevice))); // Write CompletionCode length output.Write(getInt(completionCode.Length+1)); // Write CompletionCode output.Write(getAscii(completionCode)); // Save position for later writing savePosition = output.BaseStream.Position; // Goto header length position and save the length output.BaseStream.Position = startHeader - 4; output.Write(getInt((int) (savePosition - startHeader))); output.BaseStream.Position = savePosition; // Write Lua binary code writeToMediaTable(output,0); output.Write(getInt((int)luaBinary.Length)); output.Write(luaBinary.ToArray()); // Now save all media files for (short i = 0; i < cartridge.MediaList.Count; i++) { // Write position for media table writeToMediaTable(output, (short)(i+1)); // Check media for right entry cartridge.MediaList[i].Entry = player.CheckMedia(cartridge.MediaList[i]); // Save media if (cartridge.MediaList[i].Entry == -1) { // No valid media file is found in resource list output.Write((byte) 0); } else { // Valid file found, so save type, length and bytes output.Write((byte) 1); output.Write(getInt(cartridge.MediaList[i].MediaType)); byte[] media = cartridge.MediaList[i].GetMediaAsByteArray(zip); output.Write(getInt(media.Length)); output.Write(media); } } return stream; }
/* * Executed before each test case */ public void Init() { lua = new LuaInterface(); GC.Collect(); // runs GC to expose unprotected delegates }
//internal int reference; public LuaFunction(int reference, LuaInterface interpreter) { _Reference = reference; this.function = null; _Interpreter = interpreter; }
/* * Sample test script that shows some of the capabilities of * LuaInterface */ public static void Main() { Console.WriteLine("Starting interpreter..."); LuaInterface l = new LuaInterface(); // 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 event exceptions..."); obj.TestEventException(); Console.Write("Press any key to continue..."); Console.ReadKey(true); //Console.ReadLine(); }
public static void SetLua(Lua.LuaState lua) { _interface = new LuaInterface(lua); }
/* * Executed after each test case */ public void Destroy() { lua = null; }