Example #1
0
        public static DynValue setuservalue(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var v = args.AsType(0, "setuservalue", DataType.UserData, false);
            var t = args.AsType(0, "setuservalue", DataType.Table, true);

            return v.UserData.UserValue = t;
        }
Example #2
0
        public static DynValue sort(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var vlist = args.AsType(0, "sort", DataType.Table, false);
            var lt = args[1];

            if (lt.Type != DataType.Function && lt.Type != DataType.ClrFunction && lt.IsNotNil())
                args.AsType(1, "sort", DataType.Function, true); // this throws

            var end = GetTableLength(executionContext, vlist);

            var values = new List<DynValue>();

            for (var i = 1; i <= end; i++)
                values.Add(vlist.Table.Get(i));

            try
            {
                values.Sort((a, b) => SortComparer(executionContext, a, b, lt));
            }
            catch (InvalidOperationException ex)
            {
                if (ex.InnerException is ScriptRuntimeException)
                    throw ex.InnerException;
            }

            for (var i = 0; i < values.Count; i++)
            {
                vlist.Table.Set(i + 1, values[i]);
            }

            return vlist;
        }
Example #3
0
		private static DynValue exec2n(CallbackArguments args, string funcName, double defVal, Func<double, double, double> func)
		{
			DynValue arg = args.AsType(0, funcName, DataType.Number, false);
			DynValue arg2 = args.AsType(1, funcName, DataType.Number, true);

			return DynValue.NewNumber(func(arg.Number, arg2.IsNil() ? defVal : arg2.Number));
		}
Example #4
0
        public static DynValue @char(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var sb = new StringBuilder(args.Count);

            for (var i = 0; i < args.Count; i++)
            {
                var v = args[i];
                var d = 0d;

                if (v.Type == DataType.String)
                {
                    var nd = v.CastToNumber();
                    if (nd == null)
                        args.AsType(i, "char", DataType.Number, false);
                    else
                        d = nd.Value;
                }
                else
                {
                    args.AsType(i, "char", DataType.Number, false);
                    d = v.Number;
                }

                sb.Append((char) (d));
            }

            return DynValue.NewString(sb.ToString());
        }
Example #5
0
        public static DynValue @byte(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var vs = args.AsType(0, "byte", DataType.String, false);
            var vi = args.AsType(1, "byte", DataType.Number, true);
            var vj = args.AsType(2, "byte", DataType.Number, true);

            return PerformByteLike(vs, vi, vj,
                i => Unicode2Ascii(i));
        }
Example #6
0
		public static DynValue difftime(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue t2 = args.AsType(0, "difftime", DataType.Number, false);
			DynValue t1 = args.AsType(1, "difftime", DataType.Number, true);

			if (t1.IsNil())
				return DynValue.NewNumber(t2.Number);

			return DynValue.NewNumber(t2.Number - t1.Number);
		}
Example #7
0
		public static uint Bitwise(string funcName, CallbackArguments args, Func<uint, uint, uint> accumFunc)
		{
			uint accum = ToUInt32(args.AsType(0, funcName, DataType.Number, false));

			for (int i = 1; i < args.Count; i++)
			{
				uint vv = ToUInt32(args.AsType(i, funcName, DataType.Number, false));
				accum = accumFunc(accum, vv);
			}

			return accum;
		}
        // __next_i (table [, index])
        // -------------------------------------------------------------------------------------------------------------------
        // Allows a program to traverse all fields of an array. index is an integer number
        public static DynValue __next_i(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var table = args.AsType(0, "!!next_i!!", DataType.Table);
            var index = args.AsType(1, "!!next_i!!", DataType.Number);

            var idx = ((int) index.Number) + 1;
            var val = table.Table.Get(idx);

            if (val.Type != DataType.Nil)
            {
                return DynValue.NewTuple(DynValue.NewNumber(idx), val);
            }
            return DynValue.Nil;
        }
Example #9
0
		public static DynValue setmetatable(ScriptExecutionContext executionContext, CallbackArguments args)  
		{
			DynValue table = args.AsType(0, "setmetatable", DataType.Table);
			DynValue metatable = args.AsType(1, "setmetatable", DataType.Table, true);

			DynValue curmeta = executionContext.GetMetamethod(table, "__metatable");

			if (curmeta != null)
			{
				throw new ScriptRuntimeException("cannot change a protected metatable");
			}

			table.Table.MetaTable = metatable.Table;
			return table;
		}
Example #10
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]);
		}
Example #11
0
		public static DynValue rawget(ScriptExecutionContext executionContext, CallbackArguments args)  
		{
			DynValue table = args.AsType(0, "rawget", DataType.Table);
			DynValue index = args[1];

			return table.Table.Get(index);
		}
Example #12
0
		public static DynValue execute(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue v = args.AsType(0, "execute", DataType.String, true);

			if (v.IsNil())
			{
				return DynValue.NewBoolean(true);
			}
			else
			{
				try
				{
					int exitCode = Script.GlobalOptions.Platform.OS_Execute(v.String);

					return DynValue.NewTuple(
						DynValue.Nil,
						DynValue.NewString("exit"),
						DynValue.NewNumber(exitCode));
				}
				catch (Exception)
				{
					// +++ bad to swallow.. 
					return DynValue.Nil;
				}
			}
		}
Example #13
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);
			}
		}
Example #14
0
		public static DynValue extract(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue v_v = args.AsType(0, "extract", DataType.Number);
			uint v = ToUInt32(v_v);

			DynValue v_pos = args.AsType(1, "extract", DataType.Number);
			DynValue v_width = args.AsType(2, "extract", DataType.Number, true);

			int pos = (int)v_pos.Number;
			int width = (v_width).IsNilOrNan() ? 1 : (int)v_width.Number;

			ValidatePosWidth("extract", 2, pos, width);

			uint res = (v >> pos) & NBitMask(width);
			return DynValue.NewNumber(res);
		}
Example #15
0
        public static DynValue rawset(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var table = args.AsType(0, "rawset", DataType.Table);
            var index = args[1];

            table.Table.Set(index, args[2]);

            return table;
        }
Example #16
0
		public static DynValue wrap(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			if (args[0].Type != DataType.Function && args[0].Type != DataType.ClrFunction)
				args.AsType(0, "wrap", DataType.Function); // this throws

			DynValue v = create(executionContext, args);
			DynValue c = DynValue.NewCallback(__wrap_wrapper);
			c.Callback.AdditionalData = v;
			return c;
		}
Example #17
0
        public static DynValue unpack(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var s = args.AsType(0, "unpack", DataType.Table, false);
            var vi = args.AsType(1, "unpack", DataType.Number, true);
            var vj = args.AsType(2, "unpack", DataType.Number, true);

            var ii = vi.IsNil() ? 1 : (int) vi.Number;
            var ij = vj.IsNil() ? GetTableLength(executionContext, s) : (int) vj.Number;

            var t = s.Table;

            var v = new DynValue[ij - ii + 1];

            var tidx = 0;
            for (var i = ii; i <= ij; i++)
                v[tidx++] = t.Get(i);

            return DynValue.NewTuple(v);
        }
Example #18
0
        public static DynValue getenv(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var varName = args.AsType(0, "getenv", DataType.String, false);

            var val = Script.GlobalOptions.Platform.GetEnvironmentVariable(varName.String);

            if (val == null)
                return DynValue.Nil;
            return DynValue.NewString(val);
        }
        public static DynValue next(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var table = args.AsType(0, "next", DataType.Table);
            var index = args[1];

            var pair = table.Table.NextKey(index);

            if (pair.HasValue)
                return DynValue.NewTuple(pair.Value.Key, pair.Value.Value);
            throw new ScriptRuntimeException("invalid key to 'next'");
        }
Example #20
0
		public static DynValue exit(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue v_exitCode = args.AsType(0, "exit", DataType.Number, true);
			int exitCode = 0;

			if (v_exitCode.IsNotNil())
				exitCode = (int)v_exitCode.Number;

			Script.GlobalOptions.Platform.OS_ExitFast(exitCode);

			throw new InvalidOperationException("Unreachable code.. reached.");
		}
Example #21
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);
			}
		}
		public static DynValue serialize(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			try
			{
				DynValue vt = args.AsType(0, "serialize", DataType.Table, false);
				string s = JsonTableConverter.TableToJson(vt.Table);
				return DynValue.NewString(s);
			}
			catch (SyntaxErrorException ex)
			{
				throw new ScriptRuntimeException(ex);
			}
		}
Example #23
0
		public static DynValue time(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DateTime date = DateTime.UtcNow;

			if (args.Count > 0)
			{
				DynValue vt = args.AsType(0, "time", DataType.Table, true);
				if (vt.Type == DataType.Table)
					date = ParseTimeTable(vt.Table);
			}

			return GetUnixTime(date);
		}
		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);
			}
		}
Example #25
0
		public static DynValue resume(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue handle = args.AsType(0, "resume", DataType.Thread);

			try
			{
				DynValue ret = handle.Coroutine.Resume(args.GetArray(1));

				List<DynValue> retval = new List<DynValue>();
				retval.Add(DynValue.True);

				if (ret.Type == DataType.Tuple)
				{
					for (int i = 0; i < ret.Tuple.Length; i++)
					{
						var v = ret.Tuple[i];

						if ((i == ret.Tuple.Length - 1) && (v.Type == DataType.Tuple))
						{
							retval.AddRange(v.Tuple);
						}
						else
						{
							retval.Add(v);
						}
					}
				}
				else
				{
					retval.Add(ret);
				}

				return DynValue.NewTuple(retval.ToArray());
			}
			catch (ScriptRuntimeException ex)
			{
				return DynValue.NewTuple(
					DynValue.False,
					DynValue.NewString(ex.Message));
			}
		}
Example #26
0
        public static DynValue remove(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var fileName = args.AsType(0, "remove", DataType.String, false).String;

            try
            {
                if (Script.GlobalOptions.Platform.OS_FileExists(fileName))
                {
                    Script.GlobalOptions.Platform.OS_FileDelete(fileName);
                    return DynValue.True;
                }
                return DynValue.NewTuple(
                    DynValue.Nil,
                    DynValue.NewString("{0}: No such file or directory.", fileName),
                    DynValue.NewNumber(-1));
            }
            catch (Exception ex)
            {
                return DynValue.NewTuple(DynValue.Nil, DynValue.NewString(ex.Message), DynValue.NewNumber(-1));
            }
        }
Example #27
0
        private static DynValue execaccum(CallbackArguments args, string funcName, Func<double, double, double> func)
        {
            var accum = double.NaN;

            if (args.Count == 0)
            {
                throw new ScriptRuntimeException("bad argument #1 to '{0}' (number expected, got no value)", funcName);
            }

            for (var i = 0; i < args.Count; i++)
            {
                var arg = args.AsType(i, funcName, DataType.Number, false);

                if (i == 0)
                    accum = arg.Number;
                else
                    accum = func(accum, arg.Number);
            }

            return DynValue.NewNumber(accum);
        }
Example #28
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);
            }
        }
		public static DynValue replace(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			DynValue v_v = args.AsType(0, "replace", DataType.Number);
			uint v = ToUInt32(v_v);

			DynValue v_u = args.AsType(1, "replace", DataType.Number);
			uint u = ToUInt32(v_u);
			DynValue v_pos = args.AsType(2, "replace", DataType.Number);
			DynValue v_width = args.AsType(3, "replace", DataType.Number, true);

			int pos = (int)v_pos.Number;
			int width = (v_width).IsNilOrNan() ? 1 : (int)v_width.Number;

			ValidatePosWidth("replace", 3, pos, width);

			uint mask = NBitMask(width) << pos;
			v = v & (~mask);
			u = u & (mask);
			v = v | u;

			return DynValue.NewNumber(v);
		}
Example #30
0
        public static DynValue modf(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue arg = args.AsType(0, "modf", DataType.Number, false);

            return(DynValue.NewTuple(DynValue.NewNumber(Math.Floor(arg.Number)), DynValue.NewNumber(arg.Number - Math.Floor(arg.Number))));
        }
Example #31
0
        private static DynValue exec1(CallbackArguments args, string funcName, Func <double, double> func)
        {
            DynValue arg = args.AsType(0, funcName, DataType.Number, false);

            return(DynValue.NewNumber(func(arg.Number)));
        }
Example #32
0
        public static DynValue open(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            string   filename  = args.AsType(0, "open", DataType.String, false).String;
            DynValue vmode     = args.AsType(1, "open", DataType.String, true);
            DynValue vencoding = args.AsType(2, "open", DataType.String, true);

            string mode = vmode.IsNil() ? "r" : vmode.String;

            string invalidChars = mode.Replace("+", "")
                                  .Replace("r", "")
                                  .Replace("a", "")
                                  .Replace("w", "")
                                  .Replace("b", "")
                                  .Replace("t", "");

            if (invalidChars.Length > 0)
            {
                throw ScriptRuntimeException.BadArgument(1, "open", "invalid mode");
            }


            try
            {
                string encoding = vencoding.IsNil() ? null : vencoding.String;

                // list of codes: http://msdn.microsoft.com/en-us/library/vstudio/system.text.encoding%28v=vs.90%29.aspx.
                // In addition, "binary" is available.
                Encoding e        = null;
                bool     isBinary = Framework.Do.StringContainsChar(mode, 'b');

                if (encoding == "binary")
                {
                    isBinary = true;
                    e        = new BinaryEncoding();
                }
                else if (encoding == null)
                {
                    if (!isBinary)
                    {
                        e = GetUTF8Encoding();
                    }
                    else
                    {
                        e = new BinaryEncoding();
                    }
                }
                else
                {
                    if (isBinary)
                    {
                        throw new ScriptRuntimeException("Can't specify encodings other than nil or 'binary' for binary streams.");
                    }

                    e = Encoding.GetEncoding(encoding);
                }

                return(UserData.Create(Open(executionContext, filename, e, mode)));
            }
            catch (Exception ex)
            {
                return(DynValue.NewTuple(DynValue.Nil,
                                         DynValue.NewString(IoExceptionToLuaMessage(ex, filename))));
            }
        }
Example #33
0
        public static DynValue frexp(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            // http://stackoverflow.com/questions/389993/extracting-mantissa-and-exponent-from-double-in-c-sharp

            DynValue arg = args.AsType(0, "frexp", DataType.Number, false);

            double d = arg.Number;

            // Translate the double into sign, exponent and mantissa.
            long bits = BitConverter.DoubleToInt64Bits(d);
            // Note that the shift is sign-extended, hence the test against -1 not 1
            bool negative = (bits < 0);
            int  exponent = (int)((bits >> 52) & 0x7ffL);
            long mantissa = bits & 0xfffffffffffffL;

            // Subnormal numbers; exponent is effectively one higher,
            // but there's no extra normalisation bit in the mantissa
            if (exponent == 0)
            {
                exponent++;
            }
            // Normal numbers; leave exponent as it is but add extra
            // bit to the front of the mantissa
            else
            {
                mantissa = mantissa | (1L << 52);
            }

            // Bias the exponent. It's actually biased by 1023, but we're
            // treating the mantissa as m.0 rather than 0.m, so we need
            // to subtract another 52 from it.
            exponent -= 1075;

            if (mantissa == 0)
            {
                return(DynValue.NewTuple(DynValue.NewNumber(0), DynValue.NewNumber(0)));
            }

            /* Normalize */
            while ((mantissa & 1) == 0)
            {                /*  i.e., Mantissa is even */
                mantissa >>= 1;
                exponent++;
            }

            double m = (double)mantissa;
            double e = (double)exponent;

            while (m >= 1)
            {
                m /= 2.0;
                e += 1.0;
            }

            if (negative)
            {
                m = -m;
            }

            return(DynValue.NewTuple(DynValue.NewNumber(m), DynValue.NewNumber(e)));
        }
Example #34
0
        public static DynValue len(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue vs = args.AsType(0, "len", DataType.String, false);

            return(DynValue.NewNumber(vs.String.Length));
        }
Example #35
0
        public static DynValue upper(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue arg_s = args.AsType(0, "upper", DataType.String, false);

            return(DynValue.NewString(arg_s.String.ToUpper()));
        }
Example #36
0
        public static DynValue tonumber(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            if (args.Count < 1)
            {
                throw ScriptRuntimeException.BadArgumentValueExpected(0, "tonumber");
            }

            var e = args[0];
            var b = args.AsType(1, "tonumber", DataType.Number, true);

            if (b.IsNil())
            {
                if (e.Type == DataType.Number)
                {
                    return(e);
                }

                if (e.Type != DataType.String)
                {
                    return(DynValue.Nil);
                }

                // Added support for 0x values.
                if (e.String.StartsWith("0x"))
                {
                    if (long.TryParse(e.String.AsSpan().Slice(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long l))
                    {
                        return(DynValue.NewNumber(l));
                    }

                    return(DynValue.Nil);
                }

                if (double.TryParse(e.String, NumberStyles.Any, CultureInfo.InvariantCulture, out double d))
                {
                    return(DynValue.NewNumber(d));
                }

                return(DynValue.Nil);
            }

            //!COMPAT: tonumber supports only 2,8,10 or 16 as base
            //UPDATE: added support for 3-9 base numbers
            DynValue ee;

            if (args[0].Type != DataType.Number)
            {
                ee = args.AsType(0, "tonumber", DataType.String);
            }
            else
            {
                ee = DynValue.NewString(args[0].Number.ToString(CultureInfo.InvariantCulture));
            }

            int bb = (int)b.Number;

            uint uiv = 0;

            if (bb == 2 || bb == 8 || bb == 10 || bb == 16)
            {
                uiv = Convert.ToUInt32(ee.String.Trim(), bb);
            }
            else if (bb < 10 && bb > 2) // Support for 3, 4, 5, 6, 7 and 9 based numbers
            {
                foreach (char digit in ee.String.Trim())
                {
                    int value = digit - 48;
                    if (value < 0 || value >= bb)
                    {
                        throw new ScriptRuntimeException("bad argument #1 to 'tonumber' (invalid character)");
                    }

                    uiv = (uint)(uiv * bb) + (uint)value;
                }
            }
            else
            {
                throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)");
            }

            return(DynValue.NewNumber(uiv));
        }
Example #37
0
        public static DynValue error(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var message = args.AsType(0, "error", DataType.String);

            throw new ScriptRuntimeException(message.String); // { DoNotDecorateMessage = true };
        }
Example #38
0
        public DynValue read(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            if (args.Count == 0)
            {
                string str = ReadLine();

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

                str = str.TrimEnd('\n', '\r');
                return(DynValue.NewString(str));
            }
            else
            {
                List <DynValue> rets = new List <DynValue>();

                for (int i = 0; i < args.Count; i++)
                {
                    DynValue v;

                    if (args[i].Type == DataType.Number)
                    {
                        if (Eof())
                        {
                            return(DynValue.Nil);
                        }

                        int howmany = (int)args[i].Number;

                        string str = ReadBuffer(howmany);
                        v = DynValue.NewString(str);
                    }
                    else
                    {
                        string opt = args.AsType(i, "read", DataType.String, false).String;

                        if (Eof())
                        {
                            v = opt.StartsWith("*a") ? DynValue.NewString("") : DynValue.Nil;
                        }
                        else if (opt.StartsWith("*n"))
                        {
                            double?d = ReadNumber();

                            if (d.HasValue)
                            {
                                v = DynValue.NewNumber(d.Value);
                            }
                            else
                            {
                                v = DynValue.Nil;
                            }
                        }
                        else if (opt.StartsWith("*a"))
                        {
                            string str = ReadToEnd();
                            v = DynValue.NewString(str);
                        }
                        else if (opt.StartsWith("*l"))
                        {
                            string str = ReadLine();
                            str = str.TrimEnd('\n', '\r');
                            v   = DynValue.NewString(str);
                        }
                        else if (opt.StartsWith("*L"))
                        {
                            string str = ReadLine();

                            str  = str.TrimEnd('\n', '\r');
                            str += "\n";

                            v = DynValue.NewString(str);
                        }
                        else
                        {
                            throw ScriptRuntimeException.BadArgument(i, "read", "invalid option");
                        }
                    }

                    rets.Add(v);
                }

                return(DynValue.NewTuple(rets.ToArray()));
            }
        }
Example #39
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
                {
                    TimeZoneInfo localTimeZoneInfo = executionContext.OwnerScript.Options.LocalTimeZoneInfo ?? TimeZoneInfo.Local;

                    reference = TimeZoneInfo.ConvertTimeFromUtc(reference, localTimeZoneInfo);
                    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)));
            }
        }
Example #40
0
		public static DynValue xpcall(ScriptExecutionContext executionContext, CallbackArguments args)
		{
			List<DynValue> a = new List<DynValue>();

			for (int i = 0; i < args.Count; i++)
			{
				if (i != 1)
					a.Add(args[i]);
			}

			DynValue handler = null;
			if (args[1].Type == DataType.Function || args[1].Type == DataType.ClrFunction)
			{
				handler = args[1];
			}
			else if (args[1].Type != DataType.Nil)
			{
				args.AsType(1, "xpcall", DataType.Function, false);
			}

			return SetErrorHandlerStrategy("xpcall", executionContext, new CallbackArguments(a, false), handler);
		}
Example #41
0
        public static DynValue tonumber(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            if (args.Count < 1)
            {
                throw ScriptRuntimeException.BadArgumentValueExpected(0, "tonumber");
            }

            DynValue e = args[0];
            DynValue b = args.AsType(1, "tonumber", DataType.Number, true);

            if (b.IsNil())
            {
                if (e.Type == DataType.Number)
                {
                    return(e);
                }

                if (e.Type != DataType.String)
                {
                    return(DynValue.Nil);
                }

                double?res = e.CastToNumber();
                if (res != null)
                {
                    return(DynValue.NewNumber(res.Value));
                }
                return(DynValue.Nil);
            }
            else
            {
                DynValue ee;

                if (args[0].Type != DataType.Number)
                {
                    ee = args.AsType(0, "tonumber", DataType.String, false);
                }
                else
                {
                    ee = DynValue.NewString(args[0].Number.ToString(CultureInfo.InvariantCulture));
                };
                if (ee.String.Length < 0)
                {
                    return(DynValue.Nil);
                }
                int bb = (int)b.Number;

                double uiv     = 0;
                var    trimmed = ee.String.Trim();
                if (trimmed.Length == 0)
                {
                    return(DynValue.Nil);
                }
                bool negate   = false;
                int  startIdx = 0;
                if (trimmed[0] == '-')
                {
                    negate   = true;
                    startIdx = 1;
                }
                if (trimmed[0] == '+')
                {
                    startIdx = 1;
                }
                if (bb <= 36 && bb > 1)
                {
                    for (int ij = startIdx; ij < trimmed.Length; ij++)
                    {
                        char ch = trimmed[ij];
                        int  value;
                        if (ch >= 97)
                        {
                            value = ch - 87;
                        }
                        else if (ch >= 65)
                        {
                            value = ch - 55;
                        }
                        else
                        {
                            value = ch - 48;
                        }
                        if (value < 0 || value >= bb)
                        {
                            return(DynValue.Nil);
                        }
                        uiv = uiv * bb + value;
                    }
                }
                else
                {
                    throw new ScriptRuntimeException("bad argument #2 to 'tonumber' (base out of range)");
                }

                return(DynValue.NewNumber(negate ? -uiv : uiv));
            }
        }