コード例 #1
5
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		public void CallTableFunctionTwoReturns ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("a={}\nfunction a.f(x,y)\nreturn x,x+y\nend");
				object[] ret = lua.GetFunction ("a.f").Call (3, 2);
				//Console.WriteLine("ret="+ret[0]+","+ret[1]);
				Assert.AreEqual (2, ret.Length);
				Assert.AreEqual (3, (double)ret [0]);
				Assert.AreEqual (5, (double)ret [1]);
			}
		}
コード例 #2
0
        public System.Object[] Call(string function, params System.Object[] args)
        {
            System.Object[] result = new System.Object[0];
            if (env == null)
            {
                return(result);
            }
            LuaFunction lf = env.GetFunction(function);

            if (lf == null)
            {
                return(result);
            }
            try
            {
                if (args != null)
                {
                    result = lf.Call(args);
                }
                else
                {
                    result = lf.Call();
                }
            }
            catch (NLua.Exceptions.LuaException e)
            {
                Debug.LogError(FormatException(e), gameObject);
                throw e;
            }
            return(result);
        }
コード例 #3
0
        /// <summary>
        /// Registers a command to the Lua kernel.
        /// </summary>
        /// <param name="functionName">Lua registered function name to run. Looks like "_{guildId}_{cmdName}".</param>
        /// <param name="code">Function code. Does not include the header or ending, just the body.</param>
        /// <returns></returns>
        public async Task RegisterCommand(string functionName, string code)
        {
            using var c = new CancellationTokenSource();
            c.CancelAfter(CustomCommandExecTimeout);

            await Task.Run(() =>
            {
                _luaState.DoString($"function {functionName} (args) {code} end");
                _commands[functionName] = _luaState.GetFunction(functionName);
            }, c.Token);
        }
コード例 #4
0
ファイル: LuaWatch.cs プロジェクト: SuuperW/DeSmuME-Watch
        /// <summary>
        /// A label for displaying values obtained through Lua scripts.
        /// </summary>
        /// <param name="filePath">The path to the Lua script. The script must contain a GetValue() function, which returns the desired text to be displayed.</param>
        /// <param name="lua">Obtained by calling GetLua() on a WatchManager32Bit.</param>
        public LuaWatch(string filePath, Lua.Lua lua)
        {
            NLua.Lua n = new NLua.Lua();
            n.LoadCLRPackage();
            n.DoString("import ('DeSmuME_Watch', 'DeSmuME_Watch.Lua')");

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

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

            this.AutoSize = true;
            this.SetText("?");
        }
コード例 #5
0
 /// <summary>
 /// Run the specified script.
 /// </summary>
 /// <param name="scriptFile">Script file name</param>
 public void RunScript(string scriptFile)
 {
     if (File.Exists(scriptFile))
     {
         try
         {
             using (NLua.Lua lua = new NLua.Lua())
             {
                 lua.LoadCLRPackage();
                 _luaAPI.RegisterFunctions(lua);
                 lua.DoFile(scriptFile);
                 LuaFunction fnc = lua.GetFunction("on_Run");
                 if (fnc != null)
                 {
                     fnc.Call();
                 }
             }
         }
         catch (LuaScriptException e)
         {
             MessageBox.Show(e.Message, Resources.ScriptException, MessageBoxButtons.OK);
         }
     }
 }
コード例 #6
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		public void CallGlobalFunctionOneArg ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("a=2\nfunction f(x)\na=a+x\nend");
				lua.GetFunction ("f").Call (1);
				double num = lua.GetNumber ("a");
				//Console.WriteLine("a="+num);
				Assert.AreEqual (num, 3d);
			}
		}
コード例 #7
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		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]));
			}
		}
コード例 #8
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		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);
				}
			}
		}
コード例 #9
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		private void _Calc (Lua lua, int i)
		{
			lua.DoString (
                        "sqrt = math.sqrt;" +
				"sqr = function(x) return math.pow(x,2); end;" +
				"log = math.log;" +
				"log10 = math.log10;" +
				"exp = math.exp;" +
				"sin = math.sin;" +
				"cos = math.cos;" +
				"tan = math.tan;" +
				"abs = math.abs;"
			);
			lua.DoString ("function calcVP(a,b) return a+b end");
			LuaFunction lf = lua.GetFunction ("calcVP");
			lf.Call (i, 20);
		}
コード例 #10
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();
            }
        }
コード例 #11
0
ファイル: LuaHelper.cs プロジェクト: nrother/dynamiclua
 /// <summary>
 /// Unwaps an object comming from LuaInterface for use in DynamicLua.
 /// </summary>
 public static object UnWrapObject(object wrapped, Lua state, string name = null)
 {
     if (wrapped is LuaTable)
         return new DynamicLuaTable((LuaTable)wrapped, state, name);
     else if (wrapped is LuaFunction)
         return new DynamicLuaFunction((LuaFunction)wrapped, state);
     else if (wrapped is MulticastDelegate)
         return new DynamicLuaFunction(state.GetFunction(name), state);
     else
         return wrapped;
 }
コード例 #12
0
 public void RunFunction(string function, params object[] args)
 {
     _lua.GetFunction(function).Call(args);
 }
コード例 #13
0
ファイル: LuaTests.cs プロジェクト: zhangf911/NLua
		public void CallLuaFunction()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("function someFunc(v1,v2) return v1 + v2 end");
				lua ["funcObject"] = lua.GetFunction ("someFunc");

				lua.DoString ("luanet.load_assembly('mscorlib')");
				lua.DoString ("luanet.load_assembly('NLuaTest')");
				lua.DoString ("TestClass=luanet.import_type('NLuaTest.Mock.TestClass')");
				lua.DoString ("b = TestClass():TestLuaFunction(funcObject)[0]");
				Assert.AreEqual (3, lua ["b"]);
				lua.DoString ("a = TestClass():TestLuaFunction(nil)");
				Assert.AreEqual (null, lua ["a"]);
			}
		}
コード例 #14
0
ファイル: ScriptManager.cs プロジェクト: cixonline/cixreader
        /// <summary>
        /// Load a single script from the specified manifest.
        /// </summary>
        private void LoadSingleScript(string path, ScriptManifest manifest)
        {
            string scriptFile = Path.Combine(path, manifest.ScriptFile);

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

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

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

                if (manifest.InstallToToolbar)
                {
                    ToolbarDataItem item = new ToolbarDataItem
                    {
                        type = "button",
                        name = "Script",
                        label = manifest.Name,
                        tooltip = manifest.Description,
                        data = scriptFile,
                        image = manifest.IconFile
                    };
                    CRToolbarItemCollection.DefaultCollection.Add(item);
                }
            }
            catch (Exception e)
            {
                LogFile.WriteLine("Error loading script {0} : {1}", scriptFile, e.Message);
                success = false;
            }
            if (success)
            {
                LogFile.WriteLine("Loaded and initialised script {0}", scriptFile);
            }
            else
            {
                lua.Dispose();
            }
        }
コード例 #15
0
ファイル: ScriptManager.cs プロジェクト: cixonline/cixreader
 /// <summary>
 /// Run the specified script.
 /// </summary>
 /// <param name="scriptFile">Script file name</param>
 public void RunScript(string scriptFile)
 {
     if (File.Exists(scriptFile))
     {
         try
         {
             using (NLua.Lua lua = new NLua.Lua())
             {
                 lua.LoadCLRPackage();
                 _luaAPI.RegisterFunctions(lua);
                 lua.DoFile(scriptFile);
                 LuaFunction fnc = lua.GetFunction("on_Run");
                 if (fnc != null)
                 {
                     fnc.Call();
                 }
             }
         }
         catch (LuaScriptException e)
         {
             MessageBox.Show(e.Message, Resources.ScriptException, MessageBoxButtons.OK);
         }
     }
 }
コード例 #16
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		public void CallGlobalFunctionTwoArgs ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("a=2\nfunction f(x,y)\na=x+y\nend");
				lua.GetFunction ("f").Call (1, 3);
				double num = lua.GetNumber ("a");
				//Console.WriteLine("a="+num);
				Assert.AreEqual (num, 4d);
			}
		}
コード例 #17
0
ファイル: LuaTests.cs プロジェクト: The-Megax/NLua
		public void CallGlobalFunctionOneReturn ()
		{
			using (Lua lua = new Lua ()) {
				lua.DoString ("function f(x)\nreturn x+2\nend");
				object[] ret = lua.GetFunction ("f").Call (3);
				//Console.WriteLine("ret="+ret[0]);
				Assert.AreEqual (1, ret.Length);
				Assert.AreEqual (5, (double)ret [0]);
			}
		}
コード例 #18
0
ファイル: Event.cs プロジェクト: spi8823/Sudenona
        public LuaCoroutine(Lua l)
        {
            lua = l;
            string source = Resources.Load<TextAsset>("LuaSources/Coroutine.lua").text;
            lua.DoString(source);

            startFunction = lua.GetFunction("StartCoroutines");
            updateFunction = lua.GetFunction("UpdateCoroutines");
        }
コード例 #19
0
        /// <summary>
        /// Load a single script from the specified manifest.
        /// </summary>
        private void LoadSingleScript(string path, ScriptManifest manifest)
        {
            string scriptFile = Path.Combine(path, manifest.ScriptFile);

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

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

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

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

                if (manifest.InstallToToolbar)
                {
                    ToolbarDataItem item = new ToolbarDataItem
                    {
                        type    = "button",
                        name    = "Script",
                        label   = manifest.Name,
                        tooltip = manifest.Description,
                        data    = scriptFile,
                        image   = manifest.IconFile
                    };
                    CRToolbarItemCollection.DefaultCollection.Add(item);
                }
            }
            catch (Exception e)
            {
                LogFile.WriteLine("Error loading script {0} : {1}", scriptFile, e.Message);
                success = false;
            }
            if (success)
            {
                LogFile.WriteLine("Loaded and initialised script {0}", scriptFile);
            }
            else
            {
                lua.Dispose();
            }
        }
コード例 #20
0
ファイル: LuaHelper.cs プロジェクト: qcyzj/QGS-Framework-cs
 public LuaFunction GetFunction(string func_name)
 {
     return(m_LuaState.GetFunction(func_name));
 }