Esempio n. 1
0
        private static int SortComparer(ScriptExecutionContext executionContext, DynValue a, DynValue b, DynValue lt)
        {
            if (lt.IsNil())
            {
                lt = executionContext.GetBinaryMetamethod(a, b, "__lt");

                if (lt.IsNil())
                {
                    if (a.Type == DataType.Number && b.Type == DataType.Number)
                    {
                        return(a.Number.CompareTo(b.Number));
                    }
                    if (a.Type == DataType.String && b.Type == DataType.String)
                    {
                        return(a.String.CompareTo(b.String));
                    }

                    throw ScriptRuntimeException.CompareInvalidType(a, b);
                }
                else
                {
                    return(LuaComparerToClrComparer(
                               executionContext.GetScript().Call(lt, a, b),
                               executionContext.GetScript().Call(lt, b, a)));
                }
            }
            else
            {
                return(LuaComparerToClrComparer(
                           executionContext.GetScript().Call(lt, a, b),
                           executionContext.GetScript().Call(lt, b, a)));
            }
        }
Esempio n. 2
0
        public static DynValue lines(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            string filename = args.AsType(0, "lines", DataType.String, false).String;

            try
            {
                List <DynValue> readLines = new List <DynValue>();

                using (var stream = Script.GlobalOptions.Platform.IO_OpenFile(executionContext.GetScript(), filename, null, "r"))
                {
                    using (var reader = new System.IO.StreamReader(stream))
                    {
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            readLines.Add(DynValue.NewString(line));
                        }
                    }
                }

                readLines.Add(DynValue.Nil);

                return(DynValue.FromObject(executionContext.GetScript(), readLines.Select(s => s)));
            }
            catch (Exception ex)
            {
                throw new ScriptRuntimeException(IoExceptionToLuaMessage(ex, filename));
            }
        }
Esempio n. 3
0
        public static DynValue load_impl(ScriptExecutionContext executionContext, CallbackArguments args,
                                         Table defaultEnv)
        {
            try
            {
                var    S      = executionContext.GetScript();
                var    ld     = args[0];
                string script = "";

                if (ld.Type == DataType.Function)
                {
                    while (true)
                    {
                        var ret = executionContext.GetScript().Call(ld);
                        if (ret.Type == DataType.String && ret.String.Length > 0)
                        {
                            script += ret.String;
                        }
                        else if (ret.IsNil())
                        {
                            break;
                        }
                        else
                        {
                            return(DynValue.NewTuple(DynValue.Nil,
                                                     DynValue.NewString("reader function must return a string")));
                        }
                    }
                }
                else if (ld.Type == DataType.String)
                {
                    script = ld.String;
                }
                else
                {
                    args.AsType(0, "load", DataType.Function);
                }

                var source = args.AsType(1, "load", DataType.String, true);
                var env    = args.AsType(3, "load", DataType.Table, true);

                var fn = S.LoadString(script,
                                      !env.IsNil() ? env.Table : defaultEnv,
                                      !source.IsNil() ? source.String : "=(load)");

                return(fn);
            }
            catch (SyntaxErrorException ex)
            {
                return(DynValue.NewTuple(DynValue.Nil, DynValue.NewString(ex.DecoratedMessage ?? ex.Message)));
            }
        }
Esempio n. 4
0
        static FileUserDataBase GetDefaultFile(ScriptExecutionContext executionContext, StandardFileType file)
        {
            Table R = executionContext.GetScript().Registry;

            DynValue ff = R.Get("853BEAAF298648839E2C99D005E1DF94_" + file.ToString());

            if (ff.IsNil())
            {
                ff = GetStandardFile(executionContext.GetScript(), file);
            }

            return(ff.CheckUserDataType <FileUserDataBase>("getdefaultfile(" + file.ToString() + ")"));
        }
Esempio n. 5
0
		private static DynValue __index_callback(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			string name = args[1].CastToString();

			if (name == "stdin")
				return GetStandardFile(executionContext.GetScript(), StandardFileType.StdIn);
			else if (name == "stdout")
				return GetStandardFile(executionContext.GetScript(), StandardFileType.StdOut);
			else if (name == "stderr")
				return GetStandardFile(executionContext.GetScript(), StandardFileType.StdErr);
			else
				return DynValue.Nil;
		}
Esempio n. 6
0
		static FileUserDataBase GetDefaultFile(ScriptExecutionContext executionContext, StandardFileType file)
		{
			Table R = executionContext.GetScript().Registry;

			DynValue ff = R.Get("853BEAAF298648839E2C99D005E1DF94_" + file.ToString());

			if (ff.IsNil())
			{
				ff = GetStandardFile(executionContext.GetScript(), file);
			}

			return ff.CheckUserDataType<FileUserDataBase>("getdefaultfile(" + file.ToString() + ")");
		}
Esempio n. 7
0
        public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue message = args.AsType(0, "error", DataType.String, false);
            DynValue level   = args.AsType(1, "error", DataType.Number, true);

            Coroutine cor = executionContext.GetCallingCoroutine();

            WatchItem[] stacktrace = cor.GetStackTrace(0, executionContext.CallingLocation);

            var e = new ScriptRuntimeException(message.String);

            if (level.IsNil())
            {
                level = DynValue.NewNumber(1); // Default
            }

            if (level.Number > 0 && level.Number < stacktrace.Length)
            {
                // Lua allows levels up to max. value of a double, while this has to be cast to int
                // Probably never will be a problem, just leaving this note here
                WatchItem wi = stacktrace[(int)level.Number];

                e.DecorateMessage(executionContext.GetScript(), wi.Location);
            }
            else
            {
                e.DoNotDecorateMessage = true;
            }

            throw e;
        }
Esempio n. 8
0
		public static DynValue eval(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			try
			{
				if (args[0].Type == DataType.UserData)
				{
					UserData ud = args[0].UserData;
					if (ud.Object is DynamicExprWrapper)
					{
						return ((DynamicExprWrapper)ud.Object).Expr.Evaluate(executionContext);
					}
					else
					{
						throw ScriptRuntimeException.BadArgument(0, "dynamic.eval", "A userdata was passed, but was not a previously prepared expression.");
					}
				}
				else
				{
					DynValue vs = args.AsType(0, "dynamic.eval", DataType.String, false);
					DynamicExpression expr = executionContext.GetScript().CreateDynamicExpression(vs.String);
					return expr.Evaluate(executionContext);
				}
			}
			catch (SyntaxErrorException ex)
			{ 
				throw new ScriptRuntimeException(ex);
			}
		}
Esempio n. 9
0
		public static DynValue create(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			if (args[0].Type != DataType.Function && args[0].Type != DataType.ClrFunction)
				args.AsType(0, "create", DataType.Function); // this throws

			return executionContext.GetScript().CreateCoroutine(args[0]);
		}
Esempio n. 10
0
 public static DynValue eval(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     try
     {
         if (args[0].Type == DataType.UserData)
         {
             UserData ud = args[0].UserData;
             if (ud.Object is DynamicExprWrapper)
             {
                 return(((DynamicExprWrapper)ud.Object).Expr.Evaluate(executionContext));
             }
             else
             {
                 throw ScriptRuntimeException.BadArgument(0, "dynamic.eval", "A userdata was passed, but was not a previously prepared expression.");
             }
         }
         else
         {
             DynValue          vs   = args.AsType(0, "dynamic.eval", DataType.String, false);
             DynamicExpression expr = executionContext.GetScript().CreateDynamicExpression(vs.String);
             return(expr.Evaluate(executionContext));
         }
     }
     catch (SyntaxErrorException ex)
     {
         throw new ScriptRuntimeException(ex);
     }
 }
Esempio n. 11
0
        private static DynValue MemGetLoadedTags(ScriptExecutionContext context, CallbackArguments args)
        {
            var script = context.GetScript();

            try
            {
                var table   = DynValue.NewTable(script);
                var process = GetGameProcess();
                if (process == null)
                {
                    return(table);
                }
                using (var memoryReader = new BinaryReader(new ProcessMemoryStream(process)))
                {
                    var tags = V7475GlobalIdMap.Read(process, memoryReader);
                    foreach (var pair in tags.Enumerate(memoryReader))
                    {
                        table.Table.Set(DynValue.NewNumber(pair.Key), DynValue.NewNumber(pair.Value.LocalHandle));
                    }
                }
                return(table);
            }
            catch (Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex);
#endif
                return(DynValue.NewTable(script));
            }
        }
Esempio n. 12
0
        public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var   obj  = args[0];
            Table meta = null;

            if (obj.Type.CanHaveTypeMetatables())
            {
                meta = executionContext.GetScript().GetTypeMetatable(obj.Type);
            }


            if (obj.Type == DataType.Table)
            {
                meta = obj.Table.MetaTable;
            }

            if (meta == null)
            {
                return(DynValue.Nil);
            }

            if (meta.RawGet("__metatable") != null)
            {
                return(meta.Get("__metatable"));
            }

            return(DynValue.NewTable(meta));
        }
        public static DynValue random(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue m = args.AsType(0, "random", DataType.Number, true);
            DynValue n = args.AsType(1, "random", DataType.Number, true);
            Random   R = GetRandom(executionContext.GetScript());
            double   d;

            if (m.IsNil() && n.IsNil())
            {
                d = R.NextDouble();
            }
            else
            {
                int a = n.IsNil() ? 1 : (int)n.Number;
                int b = (int)m.Number;

                if (a < b)
                {
                    d = R.Next(a, b + 1);
                }
                else
                {
                    d = R.Next(b, a + 1);
                }
            }

            return(DynValue.NewNumber(d));
        }
Esempio n. 14
0
        static FileUserDataBase GetDefaultFile(ScriptExecutionContext executionContext, DefaultFiles file)
        {
            Table R = executionContext.GetScript().Registry;

            DynValue ff = R.Get("853BEAAF298648839E2C99D005E1DF94_" + file.ToString());

            if (ff.IsNil())
            {
                switch (file)
                {
                case DefaultFiles.In:
                    return(stdin);

                case DefaultFiles.Out:
                    return(stdout);

                case DefaultFiles.Err:
                    return(stderr);

                default:
                    throw new InternalErrorException("DefaultFiles value defaulted");
                }
            }
            else
            {
                return(ff.CheckUserDataType <FileUserDataBase>("getdefaultfile(" + file.ToString() + ")"));
            }
        }
Esempio n. 15
0
        public static DynValue debug(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            Script script = executionContext.GetScript();

            while (true)
            {
                try
                {
                    string cmd = script.Options.DebugInput();

                    if (cmd == "cont")
                    {
                        return(DynValue.Void);
                    }

                    DynValue v      = script.LoadString(cmd, null, "stdin");
                    DynValue result = script.Call(v);
                    script.Options.DebugPrint(string.Format("={0}", result));
                }
                catch (ScriptRuntimeException ex)
                {
                    script.Options.DebugPrint(string.Format("{0}", ex.DecoratedMessage ?? ex.Message));
                }
                catch (Exception ex)
                {
                    script.Options.DebugPrint(string.Format("{0}", ex.Message));
                }
            }
        }
Esempio n. 16
0
		public static DynValue randomseed(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue arg = args.AsType(0, "randomseed", DataType.Number, false);
			var script = executionContext.GetScript();
			SetRandom(script, new Random((int)arg.Number));
			return DynValue.Nil;
		}
Esempio n. 17
0
        public static DynValue debug(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var script = executionContext.GetScript();

            if (script.Options.DebugInput == null)
                throw new ScriptRuntimeException("debug.debug not supported on this platform/configuration");

            var interpreter = new ReplInterpreter(script)
            {
                HandleDynamicExprs = false,
                HandleClassicExprsSyntax = true
            };

            while (true)
            {
                var s = script.Options.DebugInput(interpreter.ClassicPrompt + " ");

                try
                {
                    var result = interpreter.Evaluate(s);

                    if (result != null && result.Type != DataType.Void)
                        script.Options.DebugPrint(string.Format("{0}", result));
                }
                catch (InterpreterException ex)
                {
                    script.Options.DebugPrint(string.Format("{0}", ex.DecoratedMessage ?? ex.Message));
                }
                catch (Exception ex)
                {
                    script.Options.DebugPrint(string.Format("{0}", ex.Message));
                }
            }
        }
Esempio n. 18
0
        public static DynValue date(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DateTime reference = DateTime.UtcNow;

            DynValue vformat = args.AsType(0, "date", DataType.String, true);
            DynValue vtime   = args.AsType(1, "date", DataType.Number, true);

            string format = (vformat.IsNil()) ? "%c" : vformat.String;

            if (vtime.IsNotNil())
            {
                reference = FromUnixTime(vtime.Number);
            }

            bool isDst = false;

            if (format.StartsWith("!"))
            {
                format = format.Substring(1);
            }
            else
            {
#if !(PCL || ENABLE_DOTNET || NETFX_CORE)
                try
                {
                    reference = TimeZoneInfo.ConvertTimeFromUtc(reference, TimeZoneInfo.Local);
                    isDst     = reference.IsDaylightSavingTime();
                }
                catch (TimeZoneNotFoundException)
                {
                    // this catches a weird mono bug: https://bugzilla.xamarin.com/show_bug.cgi?id=11817
                    // however the behavior is definitely not correct. damn.
                }
#endif
            }


            if (format == "*t")
            {
                Table t = new Table(executionContext.GetScript());

                t.Set("year", DynValue.NewNumber(reference.Year));
                t.Set("month", DynValue.NewNumber(reference.Month));
                t.Set("day", DynValue.NewNumber(reference.Day));
                t.Set("hour", DynValue.NewNumber(reference.Hour));
                t.Set("min", DynValue.NewNumber(reference.Minute));
                t.Set("sec", DynValue.NewNumber(reference.Second));
                t.Set("wday", DynValue.NewNumber(((int)reference.DayOfWeek) + 1));
                t.Set("yday", DynValue.NewNumber(reference.DayOfYear));
                t.Set("isdst", DynValue.NewBoolean(isDst));

                return(DynValue.NewTable(t));
            }

            else
            {
                return(DynValue.NewString(StrFTime(format, reference)));
            }
        }
 public static DynValue create(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     if (args[0].Type != DataType.Function && args[0].Type != DataType.ClrFunction)
     {
         args.AsType(0, "create", DataType.Function);                 // this throws
     }
     return(executionContext.GetScript().CreateCoroutine(args[0]));
 }
Esempio n. 20
0
        public static DynValue __require_clr_impl(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            Script   S = executionContext.GetScript();
            DynValue v = args.AsType(0, "__require_clr_impl", DataType.String, false);

            DynValue fn = S.RequireModule(v.String);

            return(fn);            // tail call to dofile
        }
Esempio n. 21
0
		public static DynValue load_impl(ScriptExecutionContext executionContext, CallbackArguments args, Table defaultEnv)
		{
			try
			{
				Script S = executionContext.GetScript();
				DynValue ld = args[0];
				string script = "";

				if (ld.Type == DataType.Function)
				{
					while (true)
					{
						DynValue ret = executionContext.GetScript().Call(ld);
						if (ret.Type == DataType.String && ret.String.Length > 0)
							script += ret.String;
						else if (ret.IsNil())
							break;
						else
							return DynValue.NewTuple(DynValue.Nil, DynValue.NewString("reader function must return a string"));
					}
				}
				else if (ld.Type == DataType.String)
				{
					script = ld.String;
				}
				else
				{
					args.AsType(0, "load", DataType.Function, false);
				}

				DynValue source = args.AsType(1, "load", DataType.String, true);
				DynValue env = args.AsType(3, "load", DataType.Table, true);

				DynValue fn = S.LoadString(script,
					!env.IsNil() ? env.Table : defaultEnv,
					!source.IsNil() ? source.String : "=(load)");

				return fn;
			}
			catch (SyntaxErrorException ex)
			{
				return DynValue.NewTuple(DynValue.Nil, DynValue.NewString(ex.DecoratedMessage ?? ex.Message));
			}
		}
Esempio n. 22
0
        public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var v = args[0];
            var S = executionContext.GetScript();

            if (v.Type.CanHaveTypeMetatables())
                return DynValue.NewTable(S.GetTypeMetatable(v.Type));
            if (v.Type == DataType.Table)
                return DynValue.NewTable(v.Table.MetaTable);
            return DynValue.Nil;
        }
Esempio n. 23
0
        public static DynValue pack(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var t = new Table(executionContext.GetScript());
            var v = DynValue.NewTable(t);

            for (var i = 0; i < args.Count; i++)
                t.Set(i + 1, args[i]);

            t.Set("n", DynValue.NewNumber(args.Count));

            return v;
        }
		public static DynValue parse(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			try
			{
				DynValue vs = args.AsType(0, "parse", DataType.String, false);
				Table t = JsonTableConverter.JsonToTable(vs.String, executionContext.GetScript());
				return DynValue.NewTable(t);
			}
			catch (SyntaxErrorException ex)
			{
				throw new ScriptRuntimeException(ex);
			}
		}
Esempio n. 25
0
 public static DynValue parse(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     try
     {
         DynValue vs = args.AsType(0, "parse", DataType.String, false);
         DynValue parseEmptyArrays = args.AsType(1, "parse", DataType.Boolean, false);
         return(JsonTableConverter.ParseString(vs.String, executionContext.GetScript(), parseEmptyArrays.Boolean));
     }
     catch (SyntaxErrorException ex)
     {
         throw new ScriptRuntimeException(ex);
     }
 }
Esempio n. 26
0
 public static DynValue parse(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     try
     {
         var vs = args.AsType(0, "parse", DataType.String);
         var t  = JsonTableConverter.JsonToTable(vs.String, executionContext.GetScript());
         return(DynValue.NewTable(t));
     }
     catch (SyntaxErrorException ex)
     {
         throw new ScriptRuntimeException(ex);
     }
 }
Esempio n. 27
0
		public static DynValue prepare(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			try
			{
				DynValue vs = args.AsType(0, "dynamic.prepare", DataType.String, false);
				DynamicExpression expr = executionContext.GetScript().CreateDynamicExpression(vs.String);
				return UserData.Create(new DynamicExprWrapper() { Expr = expr });
			}
			catch (SyntaxErrorException ex)
			{
				throw new ScriptRuntimeException(ex);
			}
		}
Esempio n. 28
0
        public DynValue lines(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            List <DynValue> readLines = new List <DynValue>();

            DynValue readValue = null;

            do
            {
                readValue = read(executionContext, args);
                readLines.Add(readValue);
            } while (readValue.IsNotNil());

            return(DynValue.FromObject(executionContext.GetScript(), readLines.Select(s => s)));
        }
Esempio n. 29
0
        public DynValue lines(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var readLines = new List<DynValue>();

            DynValue readValue = null;

            do
            {
                readValue = read(executionContext, args);
                readLines.Add(readValue);
            } while (readValue.IsNotNil());

            return DynValue.FromObject(executionContext.GetScript(), readLines.Select(s => s));
        }
Esempio n. 30
0
        public static DynValue pack(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            Table    t = new Table(executionContext.GetScript());
            DynValue v = DynValue.NewTable(t);

            for (int i = 0; i < args.Count; i++)
            {
                t.Set(i + 1, args[i]);
            }

            t.Set("n", DynValue.NewNumber(args.Count));

            return(v);
        }
Esempio n. 31
0
 public static DynValue prepare(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     try
     {
         var vs   = args.AsType(0, "dynamic.prepare", DataType.String);
         var expr = executionContext.GetScript().CreateDynamicExpression(vs.String);
         return(UserData.Create(new DynamicExprWrapper {
             Expr = expr
         }));
     }
     catch (SyntaxErrorException ex)
     {
         throw new ScriptRuntimeException(ex);
     }
 }
Esempio n. 32
0
        private static DynValue Dump(ScriptExecutionContext context, CallbackArguments args)
        {
            var val = args.RawGet(0, true);

            if (val == null)
            {
                throw new ScriptRuntimeException("Missing a value to dump");
            }
            var maxDepthVal = args.RawGet(1, true);
            var maxDepth    = maxDepthVal != null ? (int)(maxDepthVal.CastToNumber() ?? -1) : -1;

            Dump(context.GetScript(), val, maxDepth);
            Console.WriteLine();
            return(DynValue.Void);
        }
Esempio n. 33
0
        public static DynValue pack(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            Table    t        = new Table(executionContext.GetScript());
            DynValue v        = DynValue.NewTable(t);
            int      indexFix = executionContext.OwnerScript.Options.ZeroIndexTables ? 0 : 1;

            for (int i = 0; i < args.Count; i++)
            {
                t.Set(i + indexFix, args[i]);
            }

            t.Set("n", DynValue.NewNumber(args.Count));

            return(v);
        }
Esempio n. 34
0
        public static DynValue dofile(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            try
            {
                Script   S = executionContext.GetScript();
                DynValue v = args.AsType(0, "dofile", DataType.String, false);

                DynValue fn = S.LoadFile(v.String);

                return(DynValue.NewTailCallReq(fn));                // tail call to dofile
            }
            catch (SyntaxErrorException ex)
            {
                throw new ScriptRuntimeException(ex);
            }
        }
Esempio n. 35
0
        private static DynValue loadfile_impl(ScriptExecutionContext executionContext, CallbackArguments args, Table defaultEnv)
        {
            try
            {
                Script   S        = executionContext.GetScript();
                DynValue filename = args.AsType(0, "loadfile", DataType.String, false);
                DynValue env      = args.AsType(2, "loadfile", DataType.Table, true);

                DynValue fn = S.LoadFile(filename.String, env.IsNil() ? defaultEnv : env.Table);

                return(fn);
            }
            catch (SyntaxErrorException ex)
            {
                return(DynValue.NewTuple(DynValue.Nil, DynValue.NewString(ex.Message)));
            }
        }
Esempio n. 36
0
        public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var v = args[0];
            var S = executionContext.GetScript();

            if (v.Type.CanHaveTypeMetatables())
            {
                return(DynValue.NewTable(S.GetTypeMetatable(v.Type)));
            }

            if (v.Type == DataType.Table && v.Table.MetaTable != null)
            {
                return(DynValue.NewTable(v.Table.MetaTable));
            }

            return(DynValue.Nil);
        }
Esempio n. 37
0
        public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue v = args[0];
            Script   S = executionContext.GetScript();

            if (v.Type.CanHaveTypeMetatables())
            {
                return(DynValue.NewTable(S.GetTypeMetatable(v.Type)));
            }
            else if (v.Type == DataType.Table)
            {
                return(DynValue.NewTable(v.Table.MetaTable));
            }
            else
            {
                return(DynValue.Nil);
            }
        }
Esempio n. 38
0
        private static int GetTableLength(ScriptExecutionContext executionContext, DynValue vlist)
        {
            var __len = executionContext.GetMetamethod(vlist, "__len");

            if (__len != null)
            {
                var lenv = executionContext.GetScript().Call(__len, vlist);

                var len = lenv.CastToNumber();

                if (len == null)
                {
                    throw new ScriptRuntimeException("object length is not a number");
                }

                return((int)len);
            }

            return(vlist.Table.Length);
        }
Esempio n. 39
0
        public static DynValue dump(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var fn = args.AsType(0, "dump", DataType.Function, false);

            try
            {
                byte[] bytes;
                using (var ms = new MemoryStream())
                {
                    executionContext.GetScript().Dump(fn, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    bytes = ms.ToArray();
                }
                var base64 = Convert.ToBase64String(bytes);
                return DynValue.NewString(BASE64_DUMP_HEADER + base64);
            }
            catch (Exception ex)
            {
                throw new ScriptRuntimeException(ex.Message);
            }
        }
Esempio n. 40
0
        public static DynValue dump(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue fn = args.AsType(0, "dump", DataType.Function, false);

            try
            {
                byte[] bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    executionContext.GetScript().Dump(fn, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    bytes = ms.ToArray();
                }
                string base64 = Convert.ToBase64String(bytes);
                return(DynValue.NewString(BASE64_DUMP_HEADER + base64));
            }
            catch (Exception ex)
            {
                throw new ScriptRuntimeException(ex.Message);
            }
        }
Esempio n. 41
0
        public static DynValue getmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var obj = args[0];
            Table meta = null;

            if (obj.Type.CanHaveTypeMetatables())
            {
                meta = executionContext.GetScript().GetTypeMetatable(obj.Type);
            }


            if (obj.Type == DataType.Table)
            {
                meta = obj.Table.MetaTable;
            }

            if (meta == null)
                return DynValue.Nil;
            if (meta.RawGet("__metatable") != null)
                return meta.Get("__metatable");
            return DynValue.NewTable(meta);
        }
Esempio n. 42
0
        public static DynValue setmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var v = args[0];
            var t = args.AsType(1, "setmetatable", DataType.Table, true);
            var m = (t.IsNil()) ? null : t.Table;
            var S = executionContext.GetScript();

            if (v.Type.CanHaveTypeMetatables())
            {
                S.SetTypeMetatable(v.Type, m);
            }
            else if (v.Type == DataType.Table)
            {
                v.Table.MetaTable = m;
            }
            else
            {
                throw new ScriptRuntimeException("cannot debug.setmetatable on type {0}", v.Type.ToErrorTypeString());
            }

            return(v);
        }
Esempio n. 43
0
		public static DynValue lines(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			string filename = args.AsType(0, "lines", DataType.String, false).String;

			try
			{
				List<DynValue> readLines = new List<DynValue>();

				using (var stream = Script.GlobalOptions.Platform.IO_OpenFile(executionContext.GetScript(), filename, null, "r"))
				{
					using (var reader = new System.IO.StreamReader(stream))
					{
						while (!reader.EndOfStream)
						{
							string line = reader.ReadLine();
							readLines.Add(DynValue.NewString(line));
						}
					}
				}

				readLines.Add(DynValue.Nil);

				return DynValue.FromObject(executionContext.GetScript(), readLines.Select(s => s));
			}
			catch (Exception ex)
			{
				throw new ScriptRuntimeException(IoExceptionToLuaMessage(ex, filename));
			}
		}
Esempio n. 44
0
		public static DynValue __require_clr_impl(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			Script S = executionContext.GetScript();
			DynValue v = args.AsType(0, "__require_clr_impl", DataType.String, false);

			DynValue fn = S.RequireModule(v.String);

			return fn; // tail call to dofile
		}
Esempio n. 45
0
		public static DynValue dofile(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			try
			{
				Script S = executionContext.GetScript();
				DynValue v = args.AsType(0, "dofile", DataType.String, false);

				DynValue fn = S.LoadFile(v.String);

				return DynValue.NewTailCallReq(fn); // tail call to dofile
			}
			catch (SyntaxErrorException ex)
			{
				throw new ScriptRuntimeException(ex);
			}
		}
Esempio n. 46
0
		private static DynValue loadfile_impl(ScriptExecutionContext executionContext, CallbackArguments args, Table defaultEnv)
		{
			try
			{
				Script S = executionContext.GetScript();
				DynValue filename = args.AsType(0, "loadfile", DataType.String, false);
				DynValue env = args.AsType(2, "loadfile", DataType.Table, true);

				DynValue fn = S.LoadFile(filename.String, env.IsNil() ? defaultEnv : env.Table);

				return fn;
			}
			catch (SyntaxErrorException ex)
			{
				return DynValue.NewTuple(DynValue.Nil, DynValue.NewString(ex.DecoratedMessage ?? ex.Message));
			}
		}
Esempio n. 47
0
        public static DynValue setmetatable(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var v = args[0];
            var t = args.AsType(1, "setmetatable", DataType.Table, true);
            var m = (t.IsNil()) ? null : t.Table;
            var S = executionContext.GetScript();

            if (v.Type.CanHaveTypeMetatables())
                S.SetTypeMetatable(v.Type, m);
            else if (v.Type == DataType.Table)
                v.Table.MetaTable = m;
            else
                throw new ScriptRuntimeException("cannot debug.setmetatable on type {0}", v.Type.ToErrorTypeString());

            return v;
        }
Esempio n. 48
0
		static void SetDefaultFile(ScriptExecutionContext executionContext, StandardFileType file, FileUserDataBase fileHandle)
		{
			SetDefaultFile(executionContext.GetScript(), file, fileHandle);
		}
Esempio n. 49
0
        public static DynValue random(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var m = args.AsType(0, "random", DataType.Number, true);
            var n = args.AsType(1, "random", DataType.Number, true);
            var R = GetRandom(executionContext.GetScript());
            double d;

            if (m.IsNil() && n.IsNil())
            {
                d = R.NextDouble();
            }
            else
            {
                var a = n.IsNil() ? 1 : (int) n.Number;
                var b = (int) m.Number;

                if (a < b)
                    d = R.Next(a, b + 1);
                else
                    d = R.Next(b, a + 1);
            }

            return DynValue.NewNumber(d);
        }
Esempio n. 50
0
 public static DynValue randomseed(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     var arg = args.AsType(0, "randomseed", DataType.Number, false);
     var script = executionContext.GetScript();
     SetRandom(script, new Random((int) arg.Number));
     return DynValue.Nil;
 }
Esempio n. 51
0
        public static DynValue traceback(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var sb = new StringBuilder();

            var vmessage = args[0];
            var vlevel = args[1];

            var defaultSkip = 1.0;

            var cor = executionContext.GetCallingCoroutine();

            if (vmessage.Type == DataType.Thread)
            {
                cor = vmessage.Coroutine;
                vmessage = args[1];
                vlevel = args[2];
                defaultSkip = 0.0;
            }

            if (vmessage.IsNotNil() && vmessage.Type != DataType.String && vmessage.Type != DataType.Number)
            {
                return vmessage;
            }

            var message = vmessage.CastToString();

            var skip = (int) ((vlevel.CastToNumber()) ?? defaultSkip);

            var stacktrace = cor.GetStackTrace(Math.Max(0, skip));

            if (message != null)
                sb.AppendLine(message);

            sb.AppendLine("stack traceback:");

            foreach (var wi in stacktrace)
            {
                string name;

                if (wi.Name == null)
                    if (wi.RetAddress < 0)
                        name = "main chunk";
                    else
                        name = "?";
                else
                    name = "function '" + wi.Name + "'";

                var loc = wi.Location != null ? wi.Location.FormatLocation(executionContext.GetScript()) : "[clr]";
                sb.AppendFormat("\t{0}: in {1}\n", loc, name);
            }

            return DynValue.NewString(sb);
        }
Esempio n. 52
0
 public static DynValue getregistry(ScriptExecutionContext executionContext, CallbackArguments args)
 {
     return DynValue.NewTable(executionContext.GetScript().Registry);
 }
Esempio n. 53
0
		public static DynValue date(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DateTime reference = DateTime.UtcNow;

			DynValue vformat = args.AsType(0, "date", DataType.String, true);
			DynValue vtime = args.AsType(1, "date", DataType.Number, true);

			string format = (vformat.IsNil()) ? "%c" : vformat.String;

			if (vtime.IsNotNil())
				reference = FromUnixTime(vtime.Number);

			bool isDst = false;

			if (format.StartsWith("!"))
			{
				format = format.Substring(1);
			}
			else
			{
#if !PCL
				try
				{
					reference = TimeZoneInfo.ConvertTimeFromUtc(reference, TimeZoneInfo.Local);
					isDst = reference.IsDaylightSavingTime();
				}
				catch (TimeZoneNotFoundException)
				{
					// this catches a weird mono bug: https://bugzilla.xamarin.com/show_bug.cgi?id=11817
					// however the behavior is definitely not correct. damn.
				}
#endif
			}


			if (format == "*t")
			{
				Table t = new Table(executionContext.GetScript());

				t.Set("year", DynValue.NewNumber(reference.Year));
				t.Set("month", DynValue.NewNumber(reference.Month));
				t.Set("day", DynValue.NewNumber(reference.Day));
				t.Set("hour", DynValue.NewNumber(reference.Hour));
				t.Set("min", DynValue.NewNumber(reference.Minute));
				t.Set("sec", DynValue.NewNumber(reference.Second));
				t.Set("wday", DynValue.NewNumber(((int)reference.DayOfWeek) + 1));
				t.Set("yday", DynValue.NewNumber(reference.DayOfYear));
				t.Set("isdst", DynValue.NewBoolean(isDst));

				return DynValue.NewTable(t);
			}

			else return DynValue.NewString(StrFTime(format, reference));
		}
Esempio n. 54
0
        private static int SortComparer(ScriptExecutionContext executionContext, DynValue a, DynValue b, DynValue lt)
        {
            if (lt == null || lt.IsNil())
            {
                lt = executionContext.GetBinaryMetamethod(a, b, "__lt");

                if (lt == null || lt.IsNil())
                {
                    if (a.Type == DataType.Number && b.Type == DataType.Number)
                        return a.Number.CompareTo(b.Number);
                    if (a.Type == DataType.String && b.Type == DataType.String)
                        return a.String.CompareTo(b.String);

                    throw ScriptRuntimeException.CompareInvalidType(a, b);
                }
                return LuaComparerToClrComparer(
                    executionContext.GetScript().Call(lt, a, b),
                    executionContext.GetScript().Call(lt, b, a));
            }
            return LuaComparerToClrComparer(
                executionContext.GetScript().Call(lt, a, b),
                executionContext.GetScript().Call(lt, b, a));
        }
Esempio n. 55
0
		public static DynValue print(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < args.Count; i++)
			{
				if (args[i].IsVoid())
					break;

				if (i != 0)
					sb.Append('\t');

				sb.Append(args.AsStringUsingMeta(executionContext, i, "print"));
			}

			executionContext.GetScript().Options.DebugPrint(sb.ToString());

			return DynValue.Nil;
		}
Esempio n. 56
0
		private static FileUserDataBase Open(ScriptExecutionContext executionContext, string filename, Encoding encoding, string mode)
		{
			return new FileUserData(executionContext.GetScript(), filename, encoding, mode);
		}
Esempio n. 57
0
        private static int GetTableLength(ScriptExecutionContext executionContext, DynValue vlist)
        {
            var __len = executionContext.GetMetamethod(vlist, "__len");

            if (__len != null)
            {
                var lenv = executionContext.GetScript().Call(__len, vlist);

                var len = lenv.CastToNumber();

                if (len == null)
                    throw new ScriptRuntimeException("object length is not a number");

                return (int) len;
            }
            return vlist.Table.Length;
        }