public HiddenStatefulBasicFunctions(
     LuaRuntime runtime, 
     StaticMetaTables metaTables)
 {
     _runtime = runtime;
     _metaTables = metaTables;
 }
Beispiel #2
0
 public void ImplicitBlock_Section3_3_1()
 {
     var runtime = new LuaRuntime();
     runtime.AssertedExecuteScript("a = 1; b = 'This is an implicit block.'");
     Assert.AreEqual(1, runtime["a"]);
     Assert.AreEqual("This is an implicit block.", runtime["b"]);
 }
        public void Basic()
        {
            var obj = new BasicTestObject();

            obj.a = 42;

            using (var runtime = new LuaRuntime()) {
                runtime.Globals["obj"] = new LuaTransparentClrObject(obj);

                var script = @"
                    local old_a = obj.a

                    obj.a = 50
                    obj.b = 51
                    obj.c = 'foo'
                    obj.e = 'bar'

                    return { a=old_a, n=obj.square(4), o=obj.sqr(5) }
                ";

                using (var result = runtime.DoString(script)) {
                    var t = (LuaTable)result[0];

                    Assert.AreEqual(50, obj.a, "obj.a");
                    Assert.AreEqual(51, obj.b, "obj.b");
                    Assert.AreEqual("foo", obj.C, "obj.C");
                    Assert.AreEqual("bar", obj.E, "obj.E");

                    Assert.AreEqual(42, ((LuaNumber)t["a"]).Value, "t.a");
                    Assert.AreEqual(4 * 4, ((LuaNumber)t["n"]).Value, "t.n");
                    Assert.AreEqual(5 * 5, ((LuaNumber)t["o"]).Value, "t.o");
                }
            }
        }
Beispiel #4
0
		/// <summary>
		/// Check the specified luaCode to see, if there are any errors.
		/// </summary>
		/// <param name="luaCode">String with Lua code to check.</param>
		public static void Check(string luaCode, string luaFileName)
		{
			// Create Lua runtime
			LuaRuntime luaState = new LuaRuntime ();

			// Check Lua for errors
			try {
				// Try to compile the code
				luaState.CompileString (luaCode, luaFileName);
			}
			catch (Exception ex)
			{
				// There are errors in the Lua code
				// So raise an error with the error data
				Match match = Regex.Match(ex.Message, @"(.*):(\d*):(.*)");
				int line = Convert.ToInt32(match.Groups[2].Value);
				string message = String.Format("{0}, line {1}: {2}", match.Groups[1].Value.Replace("string", "File"), match.Groups[2].Value, match.Groups[3].Value);
				string error = match.Groups[3].Value;
				string[] lines = luaCode.Replace("\r","").Split('\n');
				string code = lines.Length >= line-1 ? lines[line-1] : null;
				string before = lines.Length >= line-2 ? lines[line-2] : null;
				string after = lines.Length >= line ? lines[line] : null;

				throw new CompilerLuaException(message, line, error, code, before, after);
			}

			luaState = null;
		}
Beispiel #5
0
 public void ExplicitBlock_Section3_3_1()
 {
     var runtime = new LuaRuntime();
     var result = runtime.AssertedExecuteScript("local j = 100; do local j = 200; a = 1; b = 'This is an explicit block.'; return j end");
     Assert.AreEqual(1, runtime["a"]);
     Assert.AreEqual("This is an explicit block.", runtime["b"]);
     Assert.AreEqual(200, result);
 }
Beispiel #6
0
        public LuaValue Get(LuaRuntime runtime)
        {
            if (IsMethod)
                return runtime.CreateFunctionFromDelegate((Func<LuaVararg, LuaValue>)Invoke);

            if (IsGetProperty)
                return ((PropertyInfo)Member).GetValue(Target, null).ToLuaValue(context);

            throw new LuaException("The property '{0}' is write-only".F(Member.Name));
        }
Beispiel #7
0
        public void Boolean()
        {
            using (var runtime = new LuaRuntime()) {
                runtime.Globals["t"] = true;
                using (var t = runtime.Globals["t"]) { Assert.AreEqual(t, LuaBoolean.True); }

                runtime.Globals["t"] = false;
                using (var t = runtime.Globals["t"]) { Assert.AreEqual(t, LuaBoolean.False); }
            }
        }
		internal WIGInternalImpl(LuaRuntime luaState)
        {
			LuaTable wiginternal = luaState.CreateTable();
			luaState.Globals["WIGInternal"] = wiginternal;

			// Interface for GUI
			luaState.DoString("WIGInternal.LogMessage = function (a, b) end");
			luaState.DoString("WIGInternal.MessageBox = function (a, b, c, d, e) end");
			luaState.DoString("WIGInternal.GetInput = function (a) end");
			luaState.DoString("WIGInternal.NotifyOS = function (a) end");
			luaState.DoString("WIGInternal.ShowScreen = function (a, b) end");
			luaState.DoString("WIGInternal.ShowStatusText = function (a) end");

			// Events
			luaState.DoString("WIGInternal.AttributeChangedEvent = function (a, b) end");
			luaState.DoString("WIGInternal.CartridgeEvent = function (a) end");
			luaState.DoString("WIGInternal.CommandChangedEvent = function (a) end");
			luaState.DoString("WIGInternal.InventoryEvent = function (a, b, c) end");
			luaState.DoString("WIGInternal.MediaEvent = function (a, b) end");
			luaState.DoString("WIGInternal.TimerEvent = function (a, b) end");
			luaState.DoString("WIGInternal.ZoneStateChangedEvent = function (a) end");

			// Internal functions
			luaState.DoString("WIGInternal.IsPointInZone = function (a, b) end");
			luaState.DoString("WIGInternal.VectorToZone = function (a, b) end");
			luaState.DoString("WIGInternal.VectorToSegment = function (a, b, c) end");
			luaState.DoString("WIGInternal.VectorToPoint = function (a, b) end");
			luaState.DoString("WIGInternal.TranslatePoint = function (a, b, c) end");

            // Mark package WIGInternal as loaded
			//luaState.SafeSetGlobal("package.loaded.WIGInternal", wiginternal);
			//luaState.SafeSetGlobal("package.preload.WIGInternal", wiginternal);
			LuaTable package = (LuaTable)luaState.Globals["package"];
			LuaTable loaded = (LuaTable)package["loaded"];
			loaded["WIGInternal"] = wiginternal;
			loaded["io"] = null;
			LuaTable preload = (LuaTable)package["preload"];
			preload["WIGInternal"] = wiginternal;
			preload["io"] = null;

			// Deactivate
			luaState.Globals["io"] = null;

			// Set
			LuaTable env = (Eluant.LuaTable)luaState.CreateTable();
			luaState.Globals["Env"] = env;

            // Loads the Wherigo LUA engine.
			using (BinaryReader bw = new BinaryReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("WF.Compiler.Resources.Wherigo.luac")))
			{
			    byte[] binChunk = bw.ReadBytes ((int)bw.BaseStream.Length);

				luaState.DoString(binChunk, "Wherigo.lua");
			}
		}
Beispiel #9
0
        public void AdditionBinding()
        {
            using (var runtime = new LuaRuntime()) {
                runtime.DoString("function fn(o) return (2 + o) + 3 end").Dispose();

                using (var fn = (LuaFunction)runtime.Globals["fn"]) {
                    using (var results = fn.Call(new LuaCustomClrObject(new MathBindingObject(5)))) {
                        Console.WriteLine(results[0]);
                    }
                }
            }
        }
Beispiel #10
0
        public void Clear()
        {
            using (var runtime = new LuaRuntime()) {
                using (var t = runtime.CreateTable(Enumerable.Range(1, 100).Select(i => (LuaValue)i))) {
                    Assert.AreEqual(100, t.Count);

                    t.Clear();

                    Assert.AreEqual(0, t.Count);
                }
            }
        }
Beispiel #11
0
 public void AssignFunctionToLocalAndCall_Section3_4_9()
 {
     var runtime = new LuaRuntime();
     var printStack = new Stack<string>();
     runtime["tostring"] = (Func<object, string>) (o => o != null ? o.ToString() : "nil");
     runtime["print"] = (Action<string>) printStack.Push;
     runtime.AssertedExecuteScript(@"local boo = print; boo('Test1!'); boo('Test2!'); boo(tostring(3))");
     Assert.AreEqual("3", printStack.Pop());
     Assert.AreEqual("Test2!", printStack.Pop());
     Assert.AreEqual("Test1!", printStack.Pop());
     Assert.IsEmpty(printStack);
 }
Beispiel #12
0
 public void FunctionCallAsStatement_Section_3_3_6()
 {
     var runtime = new LuaRuntime();
     var printStack = new Stack<string>();
     runtime["tostring"] = (Func<object, string>) (o => o != null ? o.ToString() : "nil");
     runtime["print"] = (Action<string>) printStack.Push;
     runtime.AssertedExecuteScript(@"print('Test1!'); print('Test2!'); print(tostring(3))");
     Assert.AreEqual("3", printStack.Pop());
     Assert.AreEqual("Test2!", printStack.Pop());
     Assert.AreEqual("Test1!", printStack.Pop());
     Assert.IsEmpty(printStack);
 }
Beispiel #13
0
        public void DisallowCrossRuntimeReferences()
        {
            using (var runtime1 = new LuaRuntime())
            using (var runtime2 = new LuaRuntime()) {
                using (var table = runtime1.CreateTable()) {
                    Assert.Throws<InvalidOperationException>(() => runtime2.Globals["foo"] = table);

                    using (var table2 = runtime2.CreateTable()) {
                        Assert.Throws<InvalidOperationException>(() => table["foo"] = table2);
                    }
                }
            }
        }
Beispiel #14
0
        public void BasicFunction()
        {
            using (var runtime = new LuaRuntime()) {
                runtime.DoString("function basic_function(x) return x * 2 + 1 end");

                using (var fn = (LuaFunction)runtime.Globals["basic_function"]) {
                    using (var result = fn.Call(5)) {
                        Assert.AreEqual(1, result.Count, "result.Count");
                        Assert.AreEqual(11, result[0].ToNumber(), "result[0]");
                    }
                }
            }
        }
Beispiel #15
0
        public void CallbackOnCoroutineFails()
        {
            using (var runtime = new LuaRuntime()) {
                using (var callback = runtime.CreateFunctionFromDelegate(new Action(() => { Assert.Fail("Function called."); }))) {
                    runtime.Globals["callback"] = callback;
                }

                using (var r = runtime.DoString("return coroutine.resume(coroutine.create(callback))")) {
                    Assert.IsFalse(r[0].ToBoolean(), "Call succeeded.");
                    Assert.IsTrue(r[1].ToString().EndsWith("Cannot enter the CLR from inside of a Lua coroutine."), "Error message is accurate.");
                }
            }
        }
 public void ToNumberConvertsInAnyBase_Section_6_1()
 {
     var runtime = new LuaRuntime();
     runtime.Environment.ImportBasicFunctions();
     runtime.AssertedExecuteScript(
         "a = tonumber('C000', 16)\r\nb = tonumber('49152', 10)\r\nc = tonumber(140000, 8)\r\nd = tonumber('-128',10)\r\ne = tonumber('ffff', 16)\r\nf = tonumber('123')");
     Assert.AreEqual(49152, runtime["a"]);
     Assert.AreEqual(49152, runtime["b"]);
     Assert.AreEqual(49152, runtime["c"]);
     Assert.AreEqual(-128, runtime["d"]);
     Assert.AreEqual(65535, runtime["e"]);
     Assert.AreEqual(123, runtime["f"]);
 }
 public void TypeReturnsPropertStringDesignation_Section_6_1()
 {
     var runtime = new LuaRuntime();
     runtime.Environment.ImportBasicFunctions();
     runtime.AssertedExecuteScript(
         "a = type(nil)\r\nb = type('test')\r\nc = type(33)\r\nd = type(function() return 666 end)\r\ne = type(tostring)\r\nf = type(true)");
     Assert.AreEqual("nil", runtime["a"]);
     Assert.AreEqual("string", runtime["b"]);
     Assert.AreEqual("number", runtime["c"]);
     Assert.AreEqual("function", runtime["d"]);
     Assert.AreEqual("function", runtime["e"]);
     Assert.AreEqual("boolean", runtime["f"]);
 }
Beispiel #18
0
        public void Count()
        {
            using (var runtime = new LuaRuntime()) {
                using (var t = runtime.CreateTable()) {
                    Assert.AreEqual(0, t.Count);

                    t[1] = 1;
                    t[3] = "foo";
                    t["x"] = "bar";
                    t[6] = null;

                    Assert.AreEqual(3, t.Count);
                }
            }
        }
Beispiel #19
0
        public void Callback()
        {
            int? cbValue = null;
            Action<int> callback = x => cbValue = x;

            using (var runtime = new LuaRuntime()) {
                using (var wrapper = runtime.CreateFunctionFromDelegate(callback)) {
                    runtime.Globals["callback"] = wrapper;
                }

                runtime.DoString("callback(42)");
            }

            Assert.AreEqual(42, cbValue, "cbValue");
        }
Beispiel #20
0
        public void DifferentReferencesToSameClrObjectAreUnequal()
        {
            using (var runtime = new LuaRuntime()) {
                var obj = new LuaOpaqueClrObject(this);

                LuaFunction fn;
                using (var r = runtime.DoString("return function(a, b) return a == b end")) {
                    fn = (LuaFunction)r[0].CopyReference();
                }

                using (var r = fn.Call(obj, obj)) {
                    Assert.AreEqual(1, r.Count, "r.Count");
                    Assert.IsFalse(r[0].ToBoolean(), "r[0]");
                }
            }
        }
Beispiel #21
0
        public void KeysAndValues()
        {
            using (var runtime = new LuaRuntime()) {
                using (var t = runtime.CreateTable()) {
                    t[1] = 2;
                    t[3] = 4;
                    t["foo"] = "bar";

                    var keys = new HashSet<LuaValue>(new LuaValue[] { 1, 3, "foo" });
                    var values = new HashSet<LuaValue>(new LuaValue[] { 2, 4, "bar" });

                    Assert.IsTrue(keys.SetEquals(t.Keys), "Keys");
                    Assert.IsTrue(values.SetEquals(t.Values), "Values");
                }
            }
        }
Beispiel #22
0
        public LuaValue this[LuaRuntime runtime, LuaValue key]
        {
            get
            {
                switch (key.ToString())
                {
                    case "X": return X;
                    case "Y": return Y;
                    default: throw new LuaException("CPos does not define a member '{0}'".F(key));
                }
            }

            set
            {
                throw new LuaException("CPos is read-only. Use CPos.New to create a new value");
            }
        }
Beispiel #23
0
        public LuaValue this[LuaRuntime runtime, LuaValue key]
        {
            get
            {
                switch (key.ToString())
                {
                    case "X": return X;
                    case "Y": return Y;
                    case "Facing": return Traits.Util.GetFacing(this, 0);
                    default: throw new LuaException("CVec does not define a member '{0}'".F(key));
                }
            }

            set
            {
                throw new LuaException("WVec is read-only. Use CVec.New to create a new value");
            }
        }
Beispiel #24
0
		public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
		{
			get
			{
				var name = keyValue.ToString();
				ScriptMemberWrapper wrapper;
				if (!members.TryGetValue(name, out wrapper))
					throw new LuaException(MemberNotFoundError(name));

				return wrapper.Get(runtime);
			}

			set
			{
				var name = keyValue.ToString();
				ScriptMemberWrapper wrapper;
				if (!members.TryGetValue(name, out wrapper))
					throw new LuaException(MemberNotFoundError(name));

				wrapper.Set(runtime, value);
			}
		}
Beispiel #25
0
 public LuaValue ToString(LuaRuntime runtime)
 {
     return("Actor ({0})".F(this));
 }
Beispiel #26
0
 public LuaValue ToString(LuaRuntime runtime)
 {
     return("Player ({0})".F(PlayerName));
 }
Beispiel #27
0
        public static void RegisterFunctions(LuaTable module)
        {
            // cpath -> cspath?
            module.SetNameValue("cpath", new LuaString(".\\?;.\\?.dll;.\\?.exe"));
            module.SetNameValue("path", new LuaString(".\\?;.\\?.lua;.\\?.slua;.\\?.wlua;" + System.Environment.GetEnvironmentVariable("LUA_PATH")));
            module.SetNameValue("bpath", new LuaString(".\\?;.\\?.luac;.\\?.out;.\\?.sluac"));
            module.SetNameValue("loaded", new LuaTable());
            module.SetNameValue("preload", new LuaTable());
            module.Register("seeall", SeeAll);

            // Load package loader functions
            LuaTable loaderfunctions = new LuaTable();

            loaderfunctions.Register("PreloadSearcher", new LuaFunc(delegate(LuaValue[] args) {
                LuaTable t = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("preload") as LuaTable;
                string mod = (args[0] as LuaString).Text;
                LuaValue v = t.GetValue(mod);
                if (v != null && v != LuaNil.Nil)
                {
                    return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, v as LuaTable }));
                }
                else
                {
                    return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
                }
            }));

            loaderfunctions.Register("PathSearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("path").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            LuaTable m = new LuaTable();
                            m.AddValue(LuaRuntime.RunFile(fn, LuaRuntime.GlobalEnvironment));
                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, LuaRuntime.GlobalEnvironment.GetValue(Path.GetFileNameWithoutExtension(fn)) }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));

            loaderfunctions.Register("CSPathSearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("cpath").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            Console.WriteLine("Loading file '" + fn + "'...");
                            string[] modules = ExternalLibraryLoader.Load(fn);
                            LuaTable t       = LuaRuntime.GlobalEnvironment.GetValue(modules[0]) as LuaTable;

                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, t }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));
            loaderfunctions.Register("BinarySearcher", new LuaFunc(delegate(LuaValue[] args)
            {
                // get package.path variable
                string path = (LuaRuntime.GlobalEnvironment.GetValue("package") as LuaTable).GetValue("bpath").Value.ToString();
                // split into paths
                string[] paths = path.Split(';');
                // check file names
                foreach (string p in paths)
                {
                    foreach (LuaValue arg in args)
                    {
                        string sfn = arg.Value.ToString();
                        string fn  = p.Replace("?", sfn);
                        if (File.Exists(fn))
                        {
                            LuaTable m = new LuaTable();
                            bool isBreak;
                            m.AddValue((Serializer.Deserialize(fn) as AST.Chunk).Execute(LuaRuntime.GlobalEnvironment, out isBreak));
                            return(new LuaMultiValue(new LuaValue[] { LuaBoolean.True, LuaRuntime.GlobalEnvironment.GetValue(Path.GetFileNameWithoutExtension(fn)) }));
                        }
                    }
                }
                return(new LuaMultiValue(new LuaValue[] { LuaBoolean.False }));
            }));
            module.SetNameValue("loaders", loaderfunctions);
            module.Register("loadlib", new LuaFunc((LuaValue[] args) =>
            {
                return(args[0]);
            }));
        }
Beispiel #28
0
        public void WeakReferences()
        {
            using (var runtime = new LuaRuntime()) {
                LuaWeakReference<LuaTable> tableWeakRef;

                using (var table = runtime.CreateTable()) {
                    table["foo"] = "bar";

                    tableWeakRef = table.CreateWeakReference();

                    using (var tableRef = tableWeakRef.CreateReferenceToTarget()) {
                        Assert.IsNotNull(tableRef, "tableRef");
                        Assert.AreEqual("bar", tableRef["foo"].ToString(), "tableRef[\"foo\"]");
                    }
                }

                runtime.DoString("collectgarbage()");

                Assert.IsNull(tableWeakRef.CreateReferenceToTarget(), "tableWeakRef.Target");

                tableWeakRef.Dispose();
            }
        }
Beispiel #29
0
 internal LuaUserdata(LuaRuntime runtime, int reference) : base(runtime, reference)
 {
 }
Beispiel #30
0
 internal override void Push(LuaRuntime runtime)
 {
     LuaApi.lua_pushvalue(runtime.LuaState, LuaApi.LUA_GLOBALSINDEX);
 }
Beispiel #31
0
 internal LuaTable(LuaRuntime runtime, int reference) : base(runtime, reference)
 {
     Keys   = new KeyCollection(this);
     Values = new ValueCollection(this);
 }
Beispiel #32
0
 internal override void Push(LuaRuntime runtime)
 {
     LuaApi.lua_pushboolean(runtime.LuaState, Value ? 1 : 0);
 }
Beispiel #33
0
 public LuaTable GetMetatable(LuaRuntime runtime)
 {
     return(runtime.GetMetatable(this));
 }
Beispiel #34
0
 public void SetMetatable(LuaRuntime runtime, LuaTable mt)
 {
     runtime.SetMetatable(mt, this);
 }
Beispiel #35
0
        /// <summary>
        /// A REPL (Read, Eval, Print, Loop function) for #Lua
        /// </summary>
        /// <param name="args">Application startup args</param>
        public static void Main(string[] args)
        {
            // TODO: Better arg parsing/checking, make it more like the C lua

            bool GoInteractive = true;

            // Create global variables
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            //sw.Stop();
            //Console.WriteLine(sw.ElapsedMilliseconds);

#if DEBUG
#if true
            LuaRuntime.RegisterModule(typeof(TestModule));
            LuaRuntime.RegisterModule(typeof(TestModule2));
#endif

            // how to handle errors
            //LuaRuntime.SetVariable("DEBUG", true);
            LuaRuntime.SetVariable("DEBUG", false);
            // We don't need the C# traceback.
            // All it is is [error]
            //     at LuaInterface.ThrowErrorFromException
            //     [...]
            // Which we don't need
#else
            LuaRuntime.SetVariable("DEBUG", false);
#endif

            Prompt = "> ";

            bool wasSetInteract = false;
            bool wasFileRun     = false;
            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];
                if (arg.ToUpper() == "-I")
                {
                    GoInteractive  = true;
                    wasSetInteract = true;
                }
                else if (arg.ToUpper() == "-NOI")
                {
                    GoInteractive = false;
                }
                else if (arg.Substring(0, 2).ToLower() == "-l")
                {
                    if (arg.Length == 2)
                    {
                        string lib = args[++i];
                        LuaRuntime.Require(lib);
                    }
                    else
                    {
                        string lib = arg.Substring(2);
                        LuaRuntime.Require(lib);
                    }
                }
                else if (arg.ToLower() == "-e")
                {
                    if (wasSetInteract == false)
                    {
                        GoInteractive = true;
                    }

                    LuaRuntime.Run(args[++i]);

                    if (wasSetInteract == false)
                    {
                        GoInteractive = false;
                    }
                    wasFileRun = true;
                }
                else if (arg == "--")
                {
                    break;
                }
                else
                {
                    LuaTable t  = LuaRuntime.GetLua().NewTable("arg");
                    int      i3 = 1;
                    if (args.Length > i + 1)
                    {
                        for (int i2 = i + 1; i2 < args.Length; i2++)
                        {
                            t[i3++] = args[i2];
                        }
                    }

                    t[-1]  = System.Windows.Forms.Application.ExecutablePath;
                    t["n"] = t.Keys.Count;

                    if (File.Exists(args[i]))
                    {
                        LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(args[i]));
                    }
                    else
                    {
                        LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath));
                    }
                    LuaRuntime.RunFile(args[i]);

                    if (wasSetInteract == false)
                    {
                        GoInteractive = false;
                    }

                    wasFileRun = true;
                    break;
                }
            }


            /*
             * // check command line args
             * if (args.Length > 0)
             * {
             *  string file = args[0];
             *  if (File.Exists(file))
             *  {
             *      try
             *      {
             *          LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(file));
             *          LuaRuntime.RunFile(file);
             *          // it loaded successfully
             *          if (args.Length > 1 && args[1].ToUpper() != "-NOI") // possibly interactive mode after
             *              Console.WriteLine("Loaded file '" + Path.GetFileName(file) + "'");
             *      }
             *      catch (Exception error)
             *      {
             *          Console.WriteLine(error.Message);
             *      }
             *      //Console.ReadKey(true);
             *      //return;
             *      // instead, go to interactive
             *  }
             *  else
             *  {
             *      Console.WriteLine(file + " not found.");
             *  }
             * }
             */

            if (args.Length == 0)
            {
                GoInteractive = true;
            }

            if (GoInteractive)
            {
                if (args.Length == 0 || wasFileRun == false)
                {
                    LuaRuntime.PrintBanner();
                }
                LuaRuntime.SetVariable("_WORKDIR", Path.GetDirectoryName(typeof(Program).Assembly.Location));
                while (true)
                {
                    Console.Write(Prompt);
                    string line = Console.ReadLine();

                    if (line == "quit" || line == "exit" || line == "bye")
                    {
                        break;
                    }
                    else
                    {
                        try
                        {
                            object[] v = LuaRuntime.GetLua().DoString(line, "<stdin>");
                            if (v == null || v.Length == 0)
#if DEBUG
                            { Console.WriteLine("=> [no returned value]"); }
#else
                            {; }
#endif
                            else
                            {
                                Console.Write("=> ");
                                for (int i = 0; i < v.Length; i++)
                                {
                                    if (v[i] == null)
                                    {
                                        Console.WriteLine("<nil>");
                                    }
                                    else
                                    {
                                        Console.Write(v[i].ToString() + (i != v.Length - 1 ? ", " : ""));
                                    }
                                }
                                Console.WriteLine();
                            }
                        }
Beispiel #36
0
        internal object TryRun(LuaRuntime runtime, long token, object target, object[] args, out bool returned)
        {
            _Logger.Debug($"Trying to run method hook (token {token})");
            returned = false;

            object return_value = null;

            LuaFunction fun;

            if (Hooks.TryGetValue(token, out fun))
            {
                _Logger.Debug($"Hook found");
                // target == null --> static

                var objs_offs = 1;
                if (target == null)
                {
                    objs_offs = 0;
                }

                var objs = new LuaValue[args.Length + objs_offs];
                if (target != null)
                {
                    objs[0] = runtime.AsLuaValue(target);
                }
                for (int i = 0; i < args.Length; i++)
                {
                    objs[i + objs_offs] = runtime.AsLuaValue(args[i]);
                }

                var result = fun.Call(args: objs);

                Type return_type;
                if (HookReturns.TryGetValue(token, out return_type))
                {
                    if (result.Count > 1)
                    {
                        for (int i = 1; i < result.Count; i++)
                        {
                            result[i].Dispose();
                        }
                    }

                    if (result.Count > 0)
                    {
                        returned     = true;
                        return_value = runtime.ToClrObject(result[0], return_type);

                        if (return_value != result[0])
                        {
                            result[0].Dispose();
                        }
                    }
                }
                else
                {
                    result.Dispose();
                }

                for (int i = 0; i < objs.Length; i++)
                {
                    objs[i]?.Dispose();
                }
            }
            else
            {
                _Logger.Debug($"Hook not found");
            }

            return(return_value);
        }
Beispiel #37
0
 internal override void Push(LuaRuntime runtime)
 {
     LuaApi.lua_pushlstring(runtime.LuaState, Value, new UIntPtr((ulong)Value.Length));
 }
Beispiel #38
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (t != null)
            {
                if (t.ThreadState == System.Threading.ThreadState.Running)
                {
                    return;
                }
            }
            try
            {
                //if (o.Length == 2)
                {
                    t = new Thread(new ThreadStart(delegate
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        try
                        {
                            //string tmp = "return string.dump(loadstring([==============================[" + textBox1.Text + "]==============================]))";
                            string tmp = "return Load([==============================[" + textBox1.Text + "]==============================])";
                            sw.Stop();
                            object[] o       = LuaRuntime.Run(tmp);
                            LuaFunction func = o[0] as LuaFunction;
                            LuaFile f        = o[1] as LuaFile;
                            Invoke(new Action(delegate
                            {
                                textBox2.Text = "";
                                textBox2.Clear();
                                textBox3.Text = "";
                                dump(f.Main);
                            }));
                            SharpLua.Lua.OnOpcodeRun += Lua_OnOpcodeRun;
                            sw.Start();
                            //func.Call();

                            func.Call();
                            SharpLua.Lua.OnOpcodeRun -= Lua_OnOpcodeRun;
                            //func.Call();
                        }
                        catch (System.Exception ex)
                        {
                            Invoke(new Action(delegate { textBox2.Text = ex.ToString(); }));
                        }
                        finally
                        {
                            Invoke(new Action(delegate
                            {
                                sw.Stop();
                                label1.Text = "Ran in less than " + sw.ElapsedMilliseconds + " ms";
                            }));
                        }
                    }));
                    t.Start();
                }
            }
            catch (System.Exception ex)
            {
                textBox2.Text = ex.ToString();
            }
            finally
            {
            }
        }
Beispiel #39
0
 public LuaValue Minus(LuaRuntime runtime)
 {
     return(new LuaCustomClrObject(-this));
 }
Beispiel #40
0
 internal LuaGlobalsTable(LuaRuntime runtime) : base(runtime, 0)
 {
     // Finalization not required for this special reference.
     GC.SuppressFinalize(this);
 }
Beispiel #41
0
 public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
 {
     get { return(luaInterface.Value[runtime, keyValue]); }
     set { luaInterface.Value[runtime, keyValue] = value; }
 }
Beispiel #42
0
        internal override void Push(LuaRuntime runtime)
        {
            CheckDisposed();

            WeakTable.Runtime.PushWeakReference(this);
        }
Beispiel #43
0
		public LuaValue Equals (LuaRuntime runtime, LuaValue left, LuaValue right)
		{
			Player a, b;
			if (!left.TryGetClrValue<Player>(out a) || !right.TryGetClrValue<Player>(out b))
				return false;

			return a == b;
		}
Beispiel #44
0
 internal LuaFunction(LuaRuntime runtime, int reference) : base(runtime, reference)
 {
 }
Beispiel #45
0
        public void OpaqueClrObject()
        {
            using (var runtime = new LuaRuntime()) {
                runtime.Globals["o"] = new LuaOpaqueClrObject(this);

                using (var o = (LuaOpaqueClrObjectReference)runtime.Globals["o"]) {
                    Assert.AreSame(this, o.ClrObject);
                }
            }
        }
Beispiel #46
0
        public void ClrCallLoopVsVarargVsTable()
        {
            // Measures three approaches to processing 4,000 items through a Lua function fn().
            //
            // 1. Call fn() 4,000 times from C#.
            // 2. Call with 4,000 arguments a Lua function that passes each argument through fn(), returning all 4,000
            //    results.
            // 3. Build a table with 4,000 elements in C#, and pass that to a function that calls fn() on each element,
            //    replacing it with the result, and returning nothing.
            //
            // The results appear to be that 1 is fastest, 3 is very slightly slower than 1, and 2 is almost 20x slower
            // than 1.  This is good, as it means that the most straightforward and intuitive way of using Eluant in
            // such a scenario is the fastest, and that tricky optimization techniques are not required.
            const int ITEMS = 4000;

            var clrSw    = new Stopwatch();
            var varargSw = new Stopwatch();
            var tableSw  = new Stopwatch();

            IList <double> clrResults, varargResults, tableResults;

            var inputs = Enumerable.Range(1, ITEMS);

            using (var runtime = new LuaRuntime()) {
                runtime.DoString(@"
-- Main loop function
function fn(x) return x * x end

-- Function for iterating the loop in Lua and collecting the results
function loop(...)
    local function iter(x, ...)
        if x then return fn(x), iter(...) end
    end

    return iter(...)
end

-- Same, but using tables
function loop_table(t)
    for k,v in ipairs(t) do
        t[k] = fn(v)
    end
end
");
                using (var fn = (LuaFunction)runtime.Globals["fn"])
                    using (var loop = (LuaFunction)runtime.Globals["loop"])
                        using (var loop_table = (LuaFunction)runtime.Globals["loop_table"]) {
                            // CLR loop.
                            clrResults = new List <double>(ITEMS);
                            clrSw.Start();
                            foreach (var i in inputs)
                            {
                                using (var r = fn.Call(i)) {
                                    clrResults.Add(r[0].ToNumber().Value);
                                }
                            }
                            clrSw.Stop();

                            // Lua vararg.
                            varargSw.Start();
                            using (var r = loop.Call(inputs.Select(i => (LuaValue)i).ToList())) {
                                varargResults = r.Select(i => i.ToNumber().Value).ToList();
                            }
                            varargSw.Stop();

                            // Lua loop over table.
                            tableResults = new double[ITEMS];
                            tableSw.Start();
                            using (var table = runtime.CreateTable(inputs.Select(i => (LuaValue)i))) {
                                loop_table.Call(table).Dispose();

                                for (int i = 0; i < ITEMS; ++i)
                                {
                                    tableResults[i] = table[i + 1].ToNumber().Value;
                                }
                            }
                            tableSw.Stop();
                        }
            }

            Assert.IsTrue(clrResults.SequenceEqual(varargResults), "Results equal (CLR/vararg)");
            Assert.IsTrue(clrResults.SequenceEqual(tableResults), "Results equal (CLR/table)");

            Assert.Inconclusive("CLR time: {0}, Vararg time: {1}, Table time: {2}", clrSw.Elapsed, varargSw.Elapsed, tableSw.Elapsed);
        }
Beispiel #47
0
 internal LuaThread(LuaRuntime runtime, int reference) : base(runtime, reference)
 {
 }
            public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
            {
                get {
                    var members = GetMembers(keyValue);

                    if (members.Count == 1)
                    {
                        var method = members[0] as MethodInfo;
                        if (method != null)
                        {
                            return(runtime.CreateFunctionFromMethodWrapper(new LuaRuntime.MethodWrapper(clrObject.ClrObject, method)));
                        }

                        var property = members[0] as PropertyInfo;
                        if (property != null)
                        {
                            var getter = property.GetGetMethod();
                            if (getter == null)
                            {
                                throw new LuaException("Property is write-only.");
                            }
                            if (getter.GetParameters().Length != 0)
                            {
                                throw new LuaException("Cannot get an indexer.");
                            }

                            return(clrObject.Binder.ObjectToLuaValue(property.GetValue(clrObject.ClrObject, null), clrObject, runtime));
                        }

                        var field = members[0] as FieldInfo;
                        if (field != null)
                        {
                            return(clrObject.Binder.ObjectToLuaValue(field.GetValue(clrObject.ClrObject), clrObject, runtime));
                        }
                    }

                    return(LuaNil.Instance);
                }
                set {
                    var members = GetMembers(keyValue);

                    if (members.Count == 1)
                    {
                        var property = members[0] as PropertyInfo;
                        if (property != null)
                        {
                            var setter = property.GetSetMethod();
                            if (setter == null)
                            {
                                throw new LuaException("Property is read-only.");
                            }
                            if (setter.GetParameters().Length != 1)
                            {
                                throw new LuaException("Cannot set an indexer.");
                            }

                            object v;
                            try {
                                v = value.ToClrType(property.PropertyType);
                            } catch {
                                throw new LuaException("Value is incompatible with this property.");
                            }

                            property.SetValue(clrObject.ClrObject, v, null);
                            return;
                        }

                        var field = members[0] as FieldInfo;
                        if (field != null)
                        {
                            object v;
                            try {
                                v = value.ToClrType(field.FieldType);
                            } catch {
                                throw new LuaException("Value is incompatible with this property.");
                            }

                            field.SetValue(clrObject.ClrObject, v);
                            return;
                        }
                    }

                    throw new LuaException("Property/field not found: " + keyValue.ToString());
                }
            }
Beispiel #49
0
        void ConsoleIn(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                SetLuaVars();
                LCindex = 0;
                LastCommands.Add(txtConsoleIn.Text);
                if (LastCommands.Count > 26)
                {
                    LastCommands.RemoveAt(0);
                }
                txtConsole.Text += (txtConsoleIn.Text) + "\r\n";
                if (txtConsoleIn.Text.ToLower() == "start()")
                {
                    LuaRuntime.SetLua(Lua);
                    try
                    {
                        LuaRuntime.Run(txtScript.Text);
                        Start();
                    }
                    catch (Exception ex)
                    {
                        txtConsole.Text += ("LUA ERROR!!") + "\r\n";
                        txtConsole.Text += (ex.Message) + "\r\n";
                    }
                }

                else
                {
                    try
                    {
                        LuaRuntime.SetLua(Lua);
                        LuaRuntime.Run(txtConsoleIn.Text);
                    }
                    catch (Exception ex)
                    {
                        txtConsole.Text += ("LUA ERROR!!") + "\r\n";
                        txtConsole.Text += (ex.Message) + "\r\n";
                    }
                }

                txtConsoleIn.Text = "";
                GetLuaVars();
            }
            if (e.Key == Key.Up)
            {
                if (LCindex < LastCommands.Count)
                {
                    LCindex++;
                }
                if (LastCommands.Count > 0)
                {
                    txtConsoleIn.Text = LastCommands[LastCommands.Count - LCindex];
                }
            }
            if (e.Key == Key.Down)
            {
                if (LCindex > 0)
                {
                    LCindex--;
                }
                if (LCindex <= 0)
                {
                    txtConsoleIn.Text = "";
                }
                else if (LastCommands.Count > 0)
                {
                    txtConsoleIn.Text = LastCommands[LastCommands.Count - LCindex];
                }
            }
        }
 internal override void Push(LuaRuntime runtime)
 {
     runtime.PushCustomClrObject(this);
 }
Beispiel #51
0
		public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
		{
			get { return luaInterface.Value[runtime, keyValue]; }
			set { luaInterface.Value[runtime, keyValue] = value; }
		}
 internal override MetamethodAttribute[] BackingCustomObjectMetamethods(LuaRuntime runtime)
 {
     return(TransparentClrObjectProxy.Metamethods);
 }
Beispiel #53
0
		public LuaValue ToString(LuaRuntime runtime)
		{
			return "Player ({0})".F(PlayerName);
		}
Beispiel #54
0
 public LuaValue this[LuaRuntime runtime, LuaValue keyValue]
 {
     get => luaInterface.Value[runtime, keyValue];
Beispiel #55
0
        public void Table()
        {
            using (var runtime = new LuaRuntime()) {
                using (var table = runtime.CreateTable()) {
                    table["foo"] = "bar";
                    runtime.Globals["t"] = table;
                }

                using (var results = runtime.DoString("return t['foo']")) {
                    Assert.AreEqual(1, results.Count, "results.Count");
                    Assert.AreEqual("bar", results[0].ToString(), "results[0]");
                }
            }
        }
Beispiel #56
0
 public virtual LuaValue ObjectToLuaValue(object obj, IBindingContext bindingContext, LuaRuntime runtime)
 {
     return(runtime.AsLuaValue(obj) ??
            new LuaTransparentClrObject(obj, bindingContext.Binder, bindingContext.BindingSecurityPolicy));
 }
Beispiel #57
0
 internal abstract void Push(LuaRuntime runtime);
Beispiel #58
0
 public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right)
 {
     return(new LuaCustomClrObject(new MathBindingObject(1 + ToNumber(left) + ToNumber(right))));
 }
Beispiel #59
0
 internal override void Push(LuaRuntime runtime)
 {
     LuaApi.lua_pushnumber(runtime.LuaState, Value);
 }
Beispiel #60
0
        public static LuaValue LoadString(LuaValue[] values)
        {
            LuaString code = values[0] as LuaString;

            return(LuaRuntime.Run(code.Text, LuaRuntime.GlobalEnvironment));
        }