public void TestBasicFunctionality() { Lua lua = new Lua(); //// //TestLuaFunctions testLuaFunctions = new TestLuaFunctions(); //lua.RegisterFunction("Say", testLuaFunctions, testLuaFunctions.GetType().GetMethod("Say")); //lua.RegisterFunction("CreateInstance", typeof(TestLuaFunctions).GetMethod("CreateInstance")); //lua.DoString("Say('pouet')"); //lua.DoString("instance = CreateInstance()"); //lua.DoString("instance:Say('woohoo')"); //TestLuaFunctions externalInstance = (TestLuaFunctions) lua["instance"]; //externalInstance.Say("using externally created instance to call Say"); // CreateWorld(); ITestCharacter testCharacter = TestCharacter.Create(); lua["testcharacter"] = testCharacter; lua.RegisterFunction("print", typeof(LuaOutput).GetMethod("Print")); //lua["this"] = bigBadMob; //lua["room"] = DependencyContainer.Instance.GetInstance<IWorld>().Rooms.First(); lua.RegisterFunction("getCharacter", this, GetType().GetMethod("GetCharacter")); lua.DoString( @"print('this is a debug message') local this = getCharacter() cName = this.DisplayName function luanet.each(o) local e = o:GetEnumerator() return function() if e:MoveNext() then return e.Current end end end local each = luanet.each; for c in each(this.Room.People) do local name = c == getCharacter() and 'me' or c.DisplayName; print('in room:'..name); end -- local globals = _G --for g in each(globals) do -- print('global:'..tostring(g)); --end"); //doesn't work lua.DoString("function this.pouet(s) print(s) end"); var cName = lua["cName"]; var luanet = lua["luanet"]; var globals = lua["_G"]; var testCharacter2 = lua["testcharacter"]; lua.Close(); }
public void Init() { if (IsInitialized) throw new InvalidOperationException("Already Initialized!"); if (_state != null) _state.Dispose(); _state = new Lua(); _state.LoadCLRPackage(); _state.DoString(@"luanet.load_assembly('WGestures.Core'); luanet.load_assembly('WindowsInput'); luanet.load_assembly('WGestures.Common'); GestureModifier=luanet.import_type('WGestures.Core.GestureModifier'); VK=luanet.import_type('WindowsInput.Native.VirtualKeyCode'); Native=luanet.import_type('WGestures.Common.OsSpecific.Windows.Native'); ", "_init"); _state["Input"] = Sim.Simulator; _state.RegisterFunction("ReportStatus", this, typeof(ScriptCommand).GetMethod("OnReportStatus")); if(InitScript != null) { DoString(InitScript, "Init"); } IsInitialized = true; }
internal static string Execute(string content, CmdContext msg) { using (NLua.Lua lua = new NLua.Lua()) using (PrintProxy proxy = new PrintProxy()) { lua.RegisterFunction("print", proxy, proxy.GetType().GetMethod("Print", new Type[] { typeof(object[]) })); string code; using (StreamReader sr = new StreamReader(typeof(Lua).Assembly.GetManifestResourceStream("DuckBot.Resources.Sandbox.lua"))) code = sr.ReadToEnd(); try { const string template = "args = {...};rawText,sender,server,channel=args[1],args[2],args[3],args[4]\n"; string source = template + content; using (LuaFunction func = (LuaFunction)lua.DoString(code, "sandbox")[0]) { object[] rets = func.Call(source, msg.Args, msg.Sender, msg.Server, msg.Channel); if (rets.Length >= 2) { object[] arr = new object[rets.Length - 1]; Array.Copy(rets, 1, arr, 0, arr.Length); proxy.Print(arr); } string res = proxy.ToString().Trim(); return(res.Length == 0 ? msg.GetString("Strings.ret_empty_script") : res); } } catch (NLua.Exceptions.LuaScriptException ex) { return(msg.GetString("err_generic") + ": " + ex.Message + "\n``` " + ex.Source + " ```"); } } }
void Start() { lua = new NLua.Lua(); lua.LoadCLRPackage(); var method = typeof(Debug).GetMethod("Log", new Type[] { typeof(object) }); lua.RegisterFunction("print", method); }
public Task(Lua lua) { this.lua = lua; name = this.GetType ().Name.ToLower (); MethodInfo method = this.GetType ().GetMethod ("Run"); All[name] = this; lua.RegisterFunction(name, this, method); }
/// <summary>Creates a new instance of ScriptMan.</summary> /// <param name="world">The world that this script manager belongs to.</param> public ScriptMan(World world) { lua = new Lua(); map = world; lua.RegisterFunction("showMessage", this, this.GetType().GetMethod("showMessage")); lua.RegisterFunction("loadWorld", this, this.GetType().GetMethod("loadWorld")); lua.RegisterFunction("getOpenNodeIDs", this, this.GetType().GetMethod("getOpenNodeIDs")); lua.RegisterFunction("getNumOpenSegs", this, this.GetType().GetMethod("getNumOpenSegs")); lua.RegisterFunction("buildSeg", this, this.GetType().GetMethod("buildSeg")); lua.RegisterFunction("destroyNode", this, this.GetType().GetMethod("destroyNode")); lua.RegisterFunction("nodeExists", this, this.GetType().GetMethod("nodeExists")); lua.RegisterFunction("nodeActive", this, this.GetType().GetMethod("nodeActive")); lua.RegisterFunction("getConnectedNodes", this, this.GetType().GetMethod("getConnectedNodes")); }
public void Setup() { lua = new Lua (); lua.RegisterFunction ("WriteLineString", typeof (Console).GetMethod ("WriteLine", new Type [] { typeof (String) })); lua.DoString (@" function print (param) WriteLineString (tostring(param)) end "); }
private void SetupLua() { NLua.State.Encoding = Encoding.UTF8; NLua["settingsDir"] = _settings.GetSettingsDir(); NLua["storageDir"] = _settings.GetStorageDir(); NLua.RegisterFunction(nameof(Timestamp), GetStaticMethod(nameof(Timestamp))); NLua.RegisterFunction("Zip", GetStaticMethod(typeof(LuaZip), "Zip")); NLua.RegisterFunction("debugprint", GetStaticMethod("debugprint")); //NLua.RegisterFunction("CombinePath", GetStaticMethods(typeof(Path), "Combine").FirstOrDefault(x => x.GetParameters().Any(y => y.para))); foreach (MethodInfo item in GetStaticMethods(typeof(Path), "Combine")) { ParameterInfo[] p = item.GetParameters(); if (p.Any(x => x.ParameterType == typeof(string[]))) { NLua.RegisterFunction("CombinePath", item); break; } } NLua.RegisterFunction("GetNormalPath", GetStaticMethod(typeof(FileUtils), "GetNormalPath")); // nasty overload handling NLua.RegisterFunction("debugwrite", GetStaticMethods(typeof(Debug), "WriteLine") .FirstOrDefault( x => x.GetParameters() .Where(y => y.ParameterType == typeof(string)).Count() == 1)); }
public static void RegisterNLuaBox(Lua context) { context.RegisterLuaDelegateType (typeof (EventHandler<EventArgs>), typeof (LuaEventArgsHandler)); context.RegisterLuaDelegateType (typeof (EventHandler), typeof (LuaEventArgsHandler)); context.RegisterLuaDelegateType (typeof (EventHandler<UIButtonEventArgs>), typeof (LuaButtonEventArgsHandler)); context.RegisterLuaDelegateType (typeof(NSAction), typeof(LuaNSActionHandler)); context.RegisterLuaClassType (typeof (UIViewController), typeof (NLuaBoxUIViewControllerBinder)); context.RegisterLuaClassType (typeof (UITableViewSource), typeof (NLuaBoxUITableViewSourceBinder)); context.RegisterLuaClassType (typeof (JLTextViewController), typeof (NLuaBoxDetailLuaViewController)); context.RegisterLuaClassType (typeof (DialogViewController), typeof (NLuaBoxDialogViewControllerBinder)); context.RegisterLuaClassType (typeof (UITableViewController), typeof (NLuaBoxUITableViewControllerBinder)); context.RegisterFunction ("CreateListString", typeof (NLuaBoxBinder).GetMethod ("CreateListString")); }
public LuaFunction RegisterFunction(string func_name, object target) { return(m_LuaState.RegisterFunction(func_name, target, target.GetType().GetMethod(func_name))); }
protected LuaFunction RegisterFunction(string path, object target, MethodBase function) { return(_lua.RegisterFunction(path, target, function)); }
public static void Run(string scriptname, params string[] args) { try { using (Lua lua = new Lua()) { GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions(); lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer")); lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented")); lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions")); lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage")); lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage")); lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName")); lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow")); lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow")); lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand")); lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand")); lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions")); lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName")); lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow")); lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL")); lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer")); lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable")); lua.RegisterFunction("setLoginCredentials", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setLoginCredentials")); lua.RegisterFunction("joinChat", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("joinChat")); lua.RegisterFunction("setAuthCode", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("setAuthCode")); lua.RegisterFunction("connect", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("connect")); lua["args"] = args; for (int i = 1; i < args.Count(); i++) { if (i == 1) { argsJoined = args[i]; } else { argsJoined = argsJoined + " " + args[i]; } } lua["argsJoined"] = argsJoined; lua.DoFile("lua/scripts/" + scriptname + ".lua"); } } catch (Exception e) { Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString()); } }
/// <summary> /// Lua 脚本线程入口 /// </summary> private void LuaScriptStart() { using (var luaObject = new NLua.Lua()) // Lua 对象 { luaObject["C"] = this; // // 提供给 Lua 可使用的接口 luaObject.RegisterFunction("MessageBoxShow", typeof(MessageBox).GetMethod("Show", new Type[] { typeof(string) })); luaObject.RegisterFunction("CreateDataJudge", this, this.GetType().GetMethod("CreateDataJudge", new Type[] { typeof(string), typeof(string) })); luaObject.RegisterFunction("CreateDataClick", this, this.GetType().GetMethod("CreateDataClick", new Type[] { typeof(string), typeof(string) })); luaObject.RegisterFunction("Delay", this, this.GetType().GetMethod("Delay", new Type[] { typeof(int) })); luaObject.RegisterFunction("StopThread", this, this.GetType().GetMethod("StopThread")); //luaObject.RegisterFunction("Set_ChangeStatus",this,this.GetType().GetMethod("Set_ChangeStatus",new Type[] { typeof(string), typeof(Color), typeof(Color), typeof(bool)})); //luaObject.RegisterFunction("Set_AddMassage", this, this.GetType().GetMethod("Set_AddMassage", new Type[] { typeof(string) })); while (true) { Set_AddMessage($"Lua脚本:{this._scriptName} 开始执行..."); if (Cycles == 0) { } else if (ExecutedNumber >= Cycles) { break; } ExecutedNumber++; WaitQueue();// 加入到消息队列 WorkStart: try { // 改变状态栏 Set_ChangeStatus($"{ExecutedNumber}:Lua 脚本正在执行...", Color.White, Color.Orange); // 执行读入的脚本 _luaScriptText.BaseStream.Position = 0; var ret = luaObject.DoString(_luaScriptText.ReadToEnd()).First(); // 结束脚本工作 this.IsWorking = false; // 是否循环 if (Cycles == 0) { } else if (ExecutedNumber >= Cycles) { break; } Set_AddMessage($"{this._scriptName} 已挂起等待,等待时间:{WaitTime}"); Delay(2000); var wt = new TimeSpan(); while (WaitTime > 0) { wt = Functions.MillisecondToTime(WaitTime); Set_ChangeStatus($"{ExecutedNumber}:等待时间:{wt.Days * 24 + wt.Hours}:{wt.Minutes}:{wt.Seconds}", Color.White, Color.Lime); Delay(1000); WaitTime -= 1000; } } catch (ThreadAbortException) { } catch (NLua.Exceptions.LuaScriptException e)// 来自脚本的错误 { if ((e.InnerException ?? e).GetType() == typeof(Exceptions.TimeOutException)) { // 超时 OvertimeProcess(); goto WorkStart; } throw e; } } } }
public void RegisterFunctionStressTest () { const int Count = 200; // it seems to work with 41 using (Lua lua = new Lua ()) { MyClass t = new MyClass (); for (int i = 1; i < Count - 1; ++i) { lua.RegisterFunction ("func" + i, t, typeof(MyClass).GetMethod ("Func1")); } lua.RegisterFunction ("func" + (Count - 1), t, typeof(MyClass).GetMethod ("Func1")); lua.DoString ("print(func1())"); } }
public void TestEventException () { using (Lua lua = new Lua ()) { //Register a C# function MethodInfo testException = this.GetType ().GetMethod ("_TestException", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, new Type [] { typeof(float), typeof(float) }, null); lua.RegisterFunction ("Multiply", this, testException); lua.RegisterLuaDelegateType (typeof(EventHandler<EventArgs>), typeof(LuaEventArgsHandler)); //create the lua event handler code for the entity //includes the bad code! lua.DoString ("function OnClick(sender, eventArgs)\r\n" + "--Multiply expects 2 floats, but instead receives 2 strings\r\n" + "Multiply(asd, es)\r\n" + "end"); //create the lua event handler code for the entity //good code //lua.DoString("function OnClick(sender, eventArgs)\r\n" + // "--Multiply expects 2 floats\r\n" + // "Multiply(2, 50)\r\n" + // "end"); //Create the event handler script lua.DoString ("function SubscribeEntity(e)\r\ne.Clicked:Add(OnClick)\r\nend"); //Create the entity object Entity entity = new Entity (); //Register the entity object with the event handler inside lua LuaFunction lf = lua.GetFunction ("SubscribeEntity"); lf.Call (new object [1] { entity }); try { //Cause the event to be fired entity.Click (); //failed Assert.AreEqual(true, false); } catch (LuaException) { //passed Assert.AreEqual (true, true); } } }
public void TestThreading () { using (Lua lua = new Lua ()) { object lua_locker = new object (); DoWorkClass doWork = new DoWorkClass (); lua.RegisterFunction ("dowork", doWork, typeof(DoWorkClass).GetMethod ("DoWork")); bool failureDetected = false; int completed = 0; int iterations = 10; for (int i = 0; i < iterations; i++) { ThreadPool.QueueUserWorkItem (new WaitCallback (delegate (object o) { try { lock (lua_locker) { lua.DoString ("dowork()"); } } catch (Exception e) { Console.Write (e); failureDetected = true; } completed++; })); } while (completed < iterations && !failureDetected) Thread.Sleep (50); Assert.AreEqual (false, failureDetected); } }
// temple input output public static int Main(string[] args) { string output = null; string input = null; if (args.Length > 1) output = args[1]; if (args.Length > 0) input = args[0]; var arglist = args.Skip(2).ToArray(); string src; if (input != null) { using (var sr = new StreamReader(input, Encoding.UTF8)) { src = sr.ReadToEnd(); } } else { StringBuilder source = new StringBuilder(); string s; while ((s = Console.ReadLine()) != null) { source.AppendLine(s); } src = source.ToString(); } string temp = rgxVariableReplacement.Replace(src, (match) => { return "<? print(" + match.Groups["var"].Value + "); ?>"; }); var dst = rgxTextBlock.Replace("?>" + temp + "<?", (match) => { return "print(\"" + match.Groups["text"].Value.LuaEscape() + "\");\n"; }); using (currentLua = new Lua()) { currentLua["args"] = arglist; currentLua.RegisterFunction("print", typeof(MainClass).GetMethod(nameof(Print))); currentLua.DoString(Encoding.Default.GetBytes(dst), "Template")?.FirstOrDefault()?.ToString(); } currentLua = null; var result = writer.ToString(); if (output != null) { using (var sw = new StreamWriter(output, false, new UTF8Encoding(false))) { sw.Write(result); } } else { Console.Out.Write(result); } return 0; }
public void Setup() { lua = new Lua (); lua.RegisterFunction ("print", typeof (Console).GetMethod ("WriteLine", new Type [] { typeof(String) })); }
public void TestIntegration() { CreateWorld(); Lua lua = new Lua(); lua.RegisterFunction("print", typeof(LuaOutput).GetMethod("Print")); //// Create Lua table for each blueprint script table name //foreach (CharacterBlueprint blueprint in DependencyContainer.Instance.GetInstance<IWorld>().CharacterBlueprints.Where(x => x.ScriptTableName != null)) //{ // if (lua.GetTable(blueprint.ScriptTableName) == null) // lua.NewTable(blueprint.ScriptTableName); //} // Read scripts from file/immediate string lua.DoString( @" mob1 = {} function mob1:OnTick() print('OnTick:'..self.DisplayName..' '..tostring(self)); --for n in pairs(_G) do print(n) end --for n in pairs(self) do print(n) end end function mob1:OnSay(actor, msg) print('OnSay:['..self.DisplayName..'] heard ['..actor.DisplayName..'] saying ['..msg..']'); end mob2 = {} function mob2:OnTick() print('OnTick:'..self.DebugName); end function mob2:OnGreet(actor, from) print('OnGreet: ['..self.DebugName..'] saw ['..actor.DebugName..'] entering room from ['..tostring(from)..']'); actor:GainExperience(10000000); -- <-- this should be forbidden, only a few information such as DisplayName, Room, ... should be available end"); // TODO: replace 'scripts' with parameter in ICharacter and initialize this in AddCharacter or in Character ctor List <CharacterScript> scripts = new List <CharacterScript>(); foreach (ICharacter character in DependencyContainer.Instance.GetInstance <IWorld>().Characters.Where(x => x.Blueprint.ScriptTableName != null)) { string scriptName = character.Blueprint.ScriptTableName; var mobScript = lua[scriptName]; if (mobScript != null) { CharacterScript script = new CharacterScript(lua, character, scriptName); scripts.Add(script); } } // Call script from appropriate functions in Server foreach (ICharacter character in DependencyContainer.Instance.GetInstance <IWorld>().Characters) { CharacterScript script = scripts.FirstOrDefault(x => x.Character == character); script?.OnTick(); script?.OnSay(DependencyContainer.Instance.GetInstance <IWorld>().Characters.Skip(1).First(), "woot"); } CharacterScript mob1 = scripts.FirstOrDefault(x => x.Character == DependencyContainer.Instance.GetInstance <IWorld>().Characters.First()); //mob1?.Pouet("tsekwa"); CharacterScript mob2 = scripts.FirstOrDefault(x => x.Character == DependencyContainer.Instance.GetInstance <IWorld>().Characters.Skip(1).First()); mob2?.OnGreet(DependencyContainer.Instance.GetInstance <IWorld>().Characters.First(), ExitDirections.SouthWest); var mob1InLua = lua["mob1"]; lua.Close(); }
public static void Main(string[] args) { if (args.Contains("-h")) { var arglist = new List<string>(args); int index = arglist.IndexOf("-h"); HOME = arglist [index + 1]; arglist.RemoveAt(index); arglist.RemoveAt(index); args = arglist.ToArray(); } if (args.Contains("-d")) { var arglist = new List<string>(args); int index = arglist.IndexOf("-d"); CURRENT = arglist [index + 1]; arglist.RemoveAt(index); arglist.RemoveAt(index); args = arglist.ToArray(); } if (HOME == null) HOME = Directory.GetCurrentDirectory(); if (CURRENT == null) CURRENT = HOME; Directory.SetCurrentDirectory(CURRENT); if (args.Length == 0) args = new[] { "self.build" }; if (args [0] == "help") { Logger.Default .Log("> ", false, COLOR).Log ("Available commands:") .Log("./kaizow ", false, COLOR).Log ("help - display this help message") .Log("./kaizow ", false, COLOR).Log ("update (<directory>) - update kaizo from git repository or from <directory>") .Log("./kaizow ", false, COLOR).Log ("<tasks> (-arg <arguments>) - run <tasks> with optional <arguments>"); return; } else if (args [0] == "version") { Logger.Default.Log ("Kaizo ", false).Log(VERSION, true, ConsoleColor.Magenta); return; } time.Start (); Logger.Default.Log("> ", false, COLOR).Log("Build started"); Console.Write("Loading build script"); lua = new Lua (); lua.LoadCLRPackage (); lua.DoString (@" package.path = package.path..';./?/project.lua' properties = {} dependencies = { project = {}, system = {}, nuget = {} } function project(name) return module(name, package.seeall) end "); var tasks = Assembly.GetExecutingAssembly().GetTypes().Where( t => String.Equals(t.Namespace, "Kaizo.Tasks", StringComparison.Ordinal) && !String.Equals(t.Name, "Task", StringComparison.Ordinal)).ToArray(); foreach (var task in tasks) { Activator.CreateInstance(task, lua); } lua.RegisterFunction ("task", typeof(Task).GetMethod("Call")); LuaFunction project = null; try { project = lua.LoadFile (Path.Combine(CURRENT, "project.lua")); } catch (LuaScriptException e) { Fail (e); } var cmdtasks = new List<string> (args); var cmdargs = new List<string> (args); if (args.Contains ("-arg")) { int index = cmdargs.IndexOf ("-arg"); cmdargs.RemoveRange (0, index + 1); cmdtasks.RemoveRange (index, args.Length - 1); } else { cmdargs.Clear (); } var luaargs = lua.CreateTable (); foreach (var cmdarg in cmdargs) { var key = cmdarg.Replace ("\"", "").Replace ("'", "").Split ('='); luaargs [key [0]] = key [1]; } lua ["arg"] = luaargs; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine(" [DONE]"); Console.ResetColor(); project.Call(); foreach (var cmdtask in cmdtasks) { try { Task.Call (cmdtask); } catch (LuaScriptException e) { Fail (e); } catch (NotImplementedException e) { Fail (e.Message); } } Logger.Default.Log ("> ", false, ConsoleColor.Green).Log ("Build succesfull"); Finish (); }
/// <summary> /// Registers Lua functions found in the specified target. /// </summary> /// <param name="luaFunctions">Global lua function table.</param> /// <param name="target">Object (class,struct) to search in.</param> /// <param name="vm">The Lua virtual machine.</param> public static void RegisterLuaFunctions(Lua vm, ref Dictionary<string, LuaFunctionDescriptor> luaFunctions, object target) { if(vm.IsNull() || luaFunctions.IsNull()) return; var type = target.GetType(); foreach(var method in type.GetMethods()) { foreach(var attribute in Attribute.GetCustomAttributes(method)) { var attr = attribute as LuaFunctionAttribute; if(attr.IsNull()) continue; var parameters = new List<string>(); var paramInfo = method.GetParameters(); if(!attr.FunctionParameters.IsNull() && paramInfo.Length != attr.FunctionParameters.Length) { Log.Error("LuaHelper", sLConsole.GetString("Function {0} (exported as {1}): argument number mismatch. Declared {2}, but requires {3}!"), method.Name, attr.FunctionName, attr.FunctionParameters.Length, paramInfo.Length); break; } // build parameter doc hashtable. if(!attr.FunctionParameters.IsNull()) parameters.AddRange(paramInfo.Select((t, i) => string.Format("{0} - {1}", t.Name, attr.FunctionParameters[i]))); var descriptor = new LuaFunctionDescriptor(attr.FunctionName, attr.FunctionDocumentation, parameters); luaFunctions.Add(attr.FunctionName, descriptor); vm.RegisterFunction(attr.FunctionName, target, method); } } }
public Service() { this.LastAlert = new DateTime(1970, 01, 01, 0, 0, 0); this.LastENumber = ""; try { FeuerwehrCloud.Helper.Logger.WriteLine("| *** Initializing NLua..."); lua = new NLua.Lua(); lua.LoadCLRPackage(); lua ["Service"] = this; } catch (Exception ex) { if (ex.GetType().ToString() == "System.DllNotFoundException" && System.Environment.OSVersion.Platform == PlatformID.Win32NT) { // } else { // } FeuerwehrCloud.Helper.Logger.WriteLine(ex.ToString()); return; } System.IO.File.Delete("versions.txt"); System.IO.File.AppendAllText("versions.txt", System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().GetName().CodeBase) + ":" + Assembly.GetExecutingAssembly().GetName().Version.Major.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Minor.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Build.ToString() + "." + Assembly.GetExecutingAssembly().GetName().Version.Revision.ToString() + "\r\n"); var plugins = System.IO.Directory.EnumerateFiles("./plugins", "FeuerwehrCloud.*.*.dll"); //FeuerwehrCloud.Plugin.IPlugin c = new FeuerwehrCloud.Input.SMTP.SMTPSever (); foreach (string currentFile in plugins) { try { if (!System.IO.File.Exists(currentFile + ".disabled")) { var DLL = Assembly.LoadFile(currentFile); var dllVer = DLL.GetName().Version; System.IO.File.AppendAllText("versions.txt", System.IO.Path.GetFileNameWithoutExtension(currentFile) + ":" + dllVer.Major.ToString() + "." + dllVer.Minor.ToString() + "." + dllVer.Build.ToString() + "." + dllVer.Revision.ToString() + "\r\n"); foreach (Type type in DLL.GetExportedTypes()) { FeuerwehrCloud.Plugin.IPlugin c; try { c = (FeuerwehrCloud.Plugin.IPlugin)Activator.CreateInstance(type); lua[System.IO.Path.GetFileNameWithoutExtension(currentFile).Replace(".", "_")] = c; //lua[System.IO.Path.GetFileNameWithoutExtension (currentFile)] = c; lua.DebugHook += HandleDebugHook; lua.RegisterFunction(System.IO.Path.GetFileNameWithoutExtension(currentFile).Replace(".", "_") + "_Execute", c, c.GetType().GetMethod("Execute")); if (c.Initialize(this)) { //FeuerwehrCloud.Helper.Logger.WriteLine(">>>>"+System.IO.Path.GetFileNameWithoutExtension (currentFile)); PlugIns.Add(System.IO.Path.GetFileNameWithoutExtension(currentFile), c); c.Event += delegate(object sender, object[] list) { /*Xamarin.Insights.Track ("Event", new System.Collections.Generic.Dictionary<string, string> { * {"ModuleName", c.Name }, * {"ServiceType", c.ServiceType.ToString()}, * {"NextAction", sender.ToString() + ".lua" } * });*/ lua["response"] = list; switch (c.ServiceType) { case FeuerwehrCloud.Plugin.ServiceType.input: if (list [0] == "pictures") { try { //FeuerwehrCloud.Helper.Logger.WriteLine("3||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua"); //FeuerwehrCloud.Helper.Logger.WriteLine("3||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } else if (list [0] == "text") { try { //FeuerwehrCloud.Helper.Logger.WriteLine("4||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua"); //FeuerwehrCloud.Helper.Logger.WriteLine("4||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } break; case FeuerwehrCloud.Plugin.ServiceType.processor: if (list [0] == "pictures") { try { //FeuerwehrCloud.Helper.Logger.WriteLine("1||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua"); //FeuerwehrCloud.Helper.Logger.WriteLine("1||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } else if (list [0] == "text") { try { //FeuerwehrCloud.Helper.Logger.WriteLine("5||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); lua.DoFile(Application.StartupPath + "/" + sender.ToString() + ".lua"); //FeuerwehrCloud.Helper.Logger.WriteLine("5||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); try { } catch (Exception ex2) { var smtpClient = new System.Net.Mail.SmtpClient(); smtpClient.Host = "feuerwehrcloud.de"; smtpClient.Port = 25; smtpClient.EnableSsl = false; smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; var smtp = smtpClient; var mailMessage = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**"); mailMessage.Subject = "[FeuerwehrCloud] EXCEPTION AT " + System.Environment.MachineName; mailMessage.Body = FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex); using (var message = mailMessage) smtp.Send(message); } } } break; case FeuerwehrCloud.Plugin.ServiceType.output: try { //FeuerwehrCloud.Helper.Logger.WriteLine("2||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); lua.DoFile(sender.ToString() + ".lua"); //FeuerwehrCloud.Helper.Logger.WriteLine("2||||"+Application.StartupPath +"/"+ sender.ToString () + ".lua"); } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } break; } //FeuerwehrCloud.Helper.Logger.WriteLine(list[0].ToString()); }; } } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } } } catch (Exception ex) { FeuerwehrCloud.Helper.Logger.WriteLine("************ ERRROR ***************"); FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex)); } } FeuerwehrCloud.Helper.Logger.WriteLine("| Loaded plugins: " + PlugIns.Count.ToString()); lua ["PlugIns"] = PlugIns; lua.DoFile("init_complete.lua"); FeuerwehrCloud.Helper.Logger.WriteLine("| Initialisation complete. System started."); FeuerwehrCloud.Helper.Logger.WriteLine("`·--- Startup complete. ----------------------- ----- -- -"); }
public void TestCoroutine () { using (Lua lua = new Lua ()) { lua.LoadCLRPackage (); lua.RegisterFunction ("func1", null, typeof (TestClass2).GetMethod ("func")); lua.DoString ("function yielder() " + "a=1;" + "coroutine.yield();" + "func1(3,2);" + "coroutine.yield();" + // This line triggers System.NullReferenceException "a=2;" + "coroutine.yield();" + "end;" + "co_routine = coroutine.create(yielder);" + "while coroutine.resume(co_routine) do end;"); double num = lua.GetNumber ("a"); //Console.WriteLine("a="+num); Assert.AreEqual (num, 2d); } }
public static void Run(string commandname, string[] args, bool fromGroup, string ChatterID, string ChatRoomID) { try { using (Lua lua = new Lua()) { GlobalSteamLuaFunctions steamFunc = new GlobalSteamLuaFunctions(); lua.RegisterFunction("kickPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("kickPlayer")); lua.RegisterFunction("notImplemented", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("notImplemented")); lua.RegisterFunction("getPermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPermissions")); lua.RegisterFunction("sendRoomMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendRoomMessage")); lua.RegisterFunction("sendFriendMessage", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("sendFriendMessage")); //lua.RegisterFunction("convertChatIDtoSteamKit", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("convertChatIDtoSteamKit")); lua.RegisterFunction("getPersonaName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getPersonaName")); lua.RegisterFunction("addRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("addRow")); lua.RegisterFunction("getRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getRow")); lua.RegisterFunction("bindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("bindCommand")); lua.RegisterFunction("unbindCommand", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("unbindCommand")); lua.RegisterFunction("changePermissions", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changePermissions")); lua.RegisterFunction("changeName", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("changeName")); lua.RegisterFunction("likeRow", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("likeRow")); lua.RegisterFunction("getCustomURL", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("getCustomURL")); lua.RegisterFunction("banPlayer", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("banPlayer")); lua.RegisterFunction("createTable", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("createTable")); lua.RegisterFunction("silentFail", steamFunc, typeof(GlobalSteamLuaFunctions).GetMethod("silentFail")); lua["ChatterID"] = ChatterID; lua["fromGroup"] = fromGroup; lua["ChatRoomID"] = ChatRoomID; lua["args"] = args; for(int i = 1; i < args.Count(); i++) { if (i == 1) { argsJoined = args[i]; } else { argsJoined = argsJoined + " " + args[i]; } } lua["argsJoined"] = argsJoined; lua.DoFile("lua/commands/" + commandname.Substring(1) + ".lua"); } } catch (Exception e) { Log.addLog(Log.types.WARNING, "Lua", "You have an error in your command!", e.ToString()); } }
public void TestFunctions () { using (Lua lua = new Lua ()) { lua.DoString ("luanet.load_assembly('mscorlib')"); lua.DoString ("luanet.load_assembly('NLuaTest')"); lua.RegisterFunction ("p", null, typeof(System.Console).GetMethod ("WriteLine", new Type [] { typeof(String) })); /// Lua command that works (prints to console) lua.DoString ("p('Foo')"); /// Yet this works... lua.DoString ("string.gsub('some string', '(%w+)', function(s) p(s) end)"); /// This fails if you don't fix Lua5.1 lstrlib.c/add_value to treat LUA_TUSERDATA the same as LUA_FUNCTION lua.DoString ("string.gsub('some string', '(%w+)', p)"); } }
public void Init() { Lua = new Lua(); Lua.RegisterFunction("SendMessage", this, this.GetType().GetMethod("SendMessage")); Lua.RegisterFunction("RemoveItem", this, this.GetType().GetMethod("RemoveItem")); Lua.RegisterFunction("RemoveItemById", this, this.GetType().GetMethod("RemoveItemById")); Lua.RegisterFunction("UpdateHpAndMp", this, this.GetType().GetMethod("UpdateHpAndMp")); }
public void TestGenerics () { //Im not sure support for generic classes is possible to implement, see: http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.containsgenericparameters.aspx //specifically the line that says: "If the ContainsGenericParameters property returns true, the method cannot be invoked" //TestClassGeneric<string> genericClass = new TestClassGeneric<string>(); //lua.RegisterFunction("genericMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("GenericMethod")); //lua.RegisterFunction("regularMethod", genericClass, typeof(TestClassGeneric<>).GetMethod("RegularMethod")); using (Lua lua = new Lua ()) { TestClassWithGenericMethod classWithGenericMethod = new TestClassWithGenericMethod (); //////////////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////////// /// IMPORTANT: Use generic method with the type you will call or generic methods will fail with iOS /// //////////////////////////////////////////////////////////////////////// classWithGenericMethod.GenericMethod<double>(99.0); classWithGenericMethod.GenericMethod<TestClass>(new TestClass (99)); //////////////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////////// lua.RegisterFunction ("genericMethod2", classWithGenericMethod, typeof(TestClassWithGenericMethod).GetMethod ("GenericMethod")); try { lua.DoString ("genericMethod2(100)"); } catch { } Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess); Assert.AreEqual (true, classWithGenericMethod.Validate<double> (100)); //note the gotcha: numbers are all being passed to generic methods as doubles try { lua.DoString ("luanet.load_assembly('NLuaTest')"); lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')"); lua.DoString ("test=TestClass(56)"); lua.DoString ("genericMethod2(test)"); } catch { } Assert.AreEqual (true, classWithGenericMethod.GenericMethodSuccess); Assert.AreEqual (56, (classWithGenericMethod.PassedValue as TestClass).val); } }
/// <summary> /// Wraps an object to prepare it for passing to LuaInterface. If no name is specified, a /// random one with the default length is used. /// </summary> public static object WrapObject(object toWrap, Lua state, string name = null) { if (toWrap is DynamicArray) { //Someone passed an DynamicArray diretly back to Lua. //He wanted to pass the value in the array, so we extract it. //When there is more than one value, this method will ignore these extra value. //This could happen in a situation like this: lua.tmp = lua("return a,b");, but //that doesn't make sense. toWrap = (toWrap as dynamic)[0]; } if (toWrap is MulticastDelegate) { //We have to deal with a problem here: RegisterFunction does not really create //a new function, but a userdata with a __call metamethod. This works fine in all //except two cases: When Lua looks for an __index or __newindex metafunction and finds //a table or userdata, Lua tries to redirect the read/write operation to that table/userdata. //In case of our function that is in reality a userdata this fails. So we have to check //for these function and create a very thin wrapper arround this to make Lua see a function instead //the real userdata. This is no problem for the other metamethods, these are called independent //from their type. (If they are not nil ;)) MulticastDelegate function = (toWrap as MulticastDelegate); if (name != null && (name.EndsWith("__index") || name.EndsWith("__newindex"))) { string tmpName = LuaHelper.GetRandomString(); state.RegisterFunction(tmpName, function.Target, function.Method); state.DoString(String.Format("function {0}(...) return {1}(...) end", name, tmpName), "DynamicLua internal operation"); } else { if (name == null) name = LuaHelper.GetRandomString(); state.RegisterFunction(name, function.Target, function.Method); } return null; } else if (toWrap is DynamicLuaTable) { dynamic dlt = toWrap as DynamicLuaTable; return (LuaTable)dlt; } else return toWrap; }
public void TestRegisterFunction () { using (Lua lua = new Lua ()) { lua.RegisterFunction ("func1", null, typeof(TestClass2).GetMethod ("func")); object[] vals1 = lua.GetFunction ("func1").Call (2, 3); Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0])); TestClass2 obj = new TestClass2 (); lua.RegisterFunction ("func2", obj, typeof(TestClass2).GetMethod ("funcInstance")); vals1 = lua.GetFunction ("func2").Call (2, 3); Assert.AreEqual (5.0f, Convert.ToSingle (vals1 [0])); } }
public override void Run(string[] arguments) { // Correcting path => base path is package path arguments[0] = Path.Combine(Package.Directory.FullName + Path.DirectorySeparatorChar, arguments[0]); using (Lua lua = new Lua()) { lua.LoadCLRPackage(); lua.DoString("import(\"craftitude\")"); // Load craftitude assembly into Lua. lua.RegisterFunction("GetPlatformString", this, this.GetType().GetMethod("GetPlatformString")); lua.RegisterFunction("GetProfile", this, this.GetType().GetMethod("GetProfile")); lua.RegisterFunction("GetPackage", this, this.GetType().GetMethod("GetPackage")); lua.RegisterFunction("GetProfilePath", this, this.GetType().GetMethod("GetProfilePath")); lua.RegisterFunction("GetPackagePath", this, this.GetType().GetMethod("GetPackagePath")); lua.DoString(@" local mt = { } local methods = { } function mt.__index(userdata, k) if methods[k] then return methods[k] else return rawget(userdata, ""_array"")[k] end end function mt.__newindex(userdata, k, v) if methods[k] then error ""can't assign to method!"" else rawget(userdata, ""_array"")[k] = v end end"); lua.DoString(@" function import_plugin(assemblyName, namespace) import(Path.Combine(GetPluginsDir(), assemblyName)) import(namespace) end"); lua.DoString(@"function install_plugin(dllPath, assemblyName) System.IO.File.Copy(dllPath, Path.Combine(GetPluginsDir(), assemblyName .. "".dll"")) end"); lua.DoString(@"function uninstall_plugin(assemblyName) System.IO.File.Delete(Path.Combine(GetPluginsDir(), assemblyName .. "".dll"")) end"); lua.DoFile(Path.Combine(Package.Path + Path.DirectorySeparatorChar, arguments[0].Replace('/', Path.DirectorySeparatorChar))); lua.GetFunction(arguments[1]).Call(); } }
public void RegisterFunction(string path, object target, MethodBase function) { _lua.RegisterFunction(path, target, function); }
/// <summary> /// Registers a C# function with the Lua interpreter so it can be used in Lua. /// </summary> /// <param name='path'> /// The name of the function in Lua. /// </param> /// <param name='target'> /// Target object containing the registered method. /// </param> /// <param name='function'> /// The method that will be called from Lua. /// </param> public static void RegisterFunction(string path, object target, MethodInfo function) { luaVM.RegisterFunction(path, target, function); }