예제 #1
0
        public void SetColour(byte index, byte r, byte g, byte b)
        {
            if (index < 1 || index > 8)
            {
                throw ScriptRuntimeException.BadArgumentIndexOutOfRange("SetColour", 0);
            }

            if (r > 0x0F)
            {
                throw ScriptRuntimeException.BadArgument(1, "SetColour", "value is out of range (range is 0x0-0xF)");
            }

            if (g > 0x0F)
            {
                throw ScriptRuntimeException.BadArgument(2, "SetColour", "value is out of range (range is 0x0-0xF)");
            }

            if (b > 0x0F)
            {
                throw ScriptRuntimeException.BadArgument(3, "SetColour", "value is out of range (range is 0x0-0xF)");
            }

            if (!_lighting.SetColour(index, Color.FromRgb(r, g, b)))
            {
                throw new ScriptRuntimeException("rip");
            }
        }
예제 #2
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);
     }
 }
예제 #3
0
        public override long seek(string whence, long offset = 0)
        {
            CheckFileIsNotClosed();
            if (whence != null)
            {
                if (whence == "set")
                {
                    m_Stream.Seek(offset, SeekOrigin.Begin);
                }
                else if (whence == "cur")
                {
                    m_Stream.Seek(offset, SeekOrigin.Current);
                }
                else if (whence == "end")
                {
                    m_Stream.Seek(offset, SeekOrigin.End);
                }
                else
                {
                    throw ScriptRuntimeException.BadArgument(0, "seek", "invalid option '" + whence + "'");
                }
            }

            return(m_Stream.Position);
        }
예제 #4
0
        public static DynValue upvaluejoin(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue f1 = args.AsType(0, "upvaluejoin", DataType.Function, false);
            DynValue f2 = args.AsType(2, "upvaluejoin", DataType.Function, false);
            int      n1 = args.AsInt(1, "upvaluejoin") - 1;
            int      n2 = args.AsInt(3, "upvaluejoin") - 1;

            Closure c1 = f1.Function;
            Closure c2 = f2.Function;

            if (n1 < 0 || n1 >= c1.ClosureContext.Count)
            {
                throw ScriptRuntimeException.BadArgument(1, "upvaluejoin", "invalid upvalue index");
            }

            if (n2 < 0 || n2 >= c2.ClosureContext.Count)
            {
                throw ScriptRuntimeException.BadArgument(3, "upvaluejoin", "invalid upvalue index");
            }

            var d = c1.ClosureContext[n1];

            c2.ClosureContext.ReplaceWith(n2, c1.ClosureContext[n1]);

            return(DynValue.Void);
        }
예제 #5
0
        public static DynValue rawlen(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            if (args[0].Type != DataType.String && args[0].Type != DataType.Table)
            {
                throw ScriptRuntimeException.BadArgument(0, "rawlen", "table or string", args[0].Type.ToErrorTypeString(), false);
            }

            return(args[0].GetLength());
        }
        /// <summary>
        /// Performs an "index" "get" operation. This tries to resolve minor variations of member names.
        /// </summary>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="index">The index.</param>
        /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
        /// <returns></returns>
        public virtual DynValue Index(Script script, object obj, DynValue index, bool isDirectIndexing)
        {
            if (!isDirectIndexing)
            {
                StandardUserDataOverloadedMethodDescriptor mdesc = m_Methods.GetOrDefault(SPECIAL_GETITEM);

                if (mdesc != null)
                {
                    return(ExecuteIndexer(mdesc, script, obj, index, null));
                }
            }

            index = index.ToScalar();

            if (index.Type != DataType.String)
            {
                throw ScriptRuntimeException.BadArgument(1, string.Format("userdata<{0}>.__index", this.Name), "string", index.Type.ToLuaTypeString(), false);
            }

            DynValue v = TryIndex(script, obj, index.String);

            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, Camelify(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(Camelify(index.String)));
            }

            if (v == null && m_ExtMethodsVersion < UserData.GetExtensionMethodsChangeVersion())
            {
                m_ExtMethodsVersion = UserData.GetExtensionMethodsChangeVersion();

                v = TryIndexOnExtMethod(script, obj, index.String);
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, UpperFirstLetter(index.String));
                }
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, Camelify(index.String));
                }
                if (v == null)
                {
                    v = TryIndexOnExtMethod(script, obj, UpperFirstLetter(Camelify(index.String)));
                }
            }

            return(v);
        }
예제 #7
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 = mode.Contains('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)));
			}

		}
예제 #8
0
        private static void RegisterSleepFunction(ExecutionConstrainedScript script, ManualResetEventSlim scriptThreadShutdownEvent)
        {
            script.Globals.Get("os").Table["sleep"] = (Action <double>)((double ms) =>
            {
                if (ms <= 0)
                {
                    throw ScriptRuntimeException.BadArgument(0, "sleep", "not a positive number");
                }

                scriptThreadShutdownEvent.Wait(TimeSpan.FromMilliseconds(ms));
            });
        }
예제 #9
0
        private static DynValue clr_iterator_next(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue userdata = args.AsType(0, "clr_iterator_next", DataType.UserData);
            DynValue prev     = args[1];

            UserData          ud       = userdata.UserData;
            EnumerableWrapper iterator = ud.Object as EnumerableWrapper;

            if (iterator == null)
            {
                throw ScriptRuntimeException.BadArgument(0, "clr_iterator_next",
                                                         (ud.Object != null) ? ud.Object.GetType().FullName : "null",
                                                         typeof(EnumerableWrapper).FullName,
                                                         false);
            }

            return(iterator.GetNext(prev));
        }
예제 #10
0
        public static DynValue insert(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            DynValue vlist  = args.AsType(0, "table.insert", DataType.Table, false);
            DynValue vpos   = args[1];
            DynValue vvalue = args[2];

            if (args.Count > 3)
            {
                throw new ScriptRuntimeException("wrong number of arguments to 'insert'");
            }

            int   len  = GetTableLength(executionContext, vlist);
            Table list = vlist.Table;

            if (vvalue.IsNil())
            {
                vvalue = vpos;
                vpos   = DynValue.NewNumber(len + (executionContext.OwnerScript.Options.ZeroIndexTables ? 0 : 1));               // + 1
            }

            if (vpos.Type != DataType.Number)
            {
                throw ScriptRuntimeException.BadArgument(1, "table.insert", DataType.Number, vpos.Type, false);
            }

            int pos = (int)vpos.Number;

            if (pos > len + 1 || pos < (executionContext.OwnerScript.Options.ZeroIndexTables ? 0 : 1))
            {
                throw new ScriptRuntimeException("bad argument #2 to 'insert' (position out of bounds)");
            }

            for (int i = len; i >= pos; i--)
            {
                list.Set(i + 1, list.Get(i));
            }

            list.Set(pos, vvalue);

            return(vlist);
        }
예제 #11
0
        public DynValue GetSensorValue(string label)
        {
            if (allowedLabels.Find(x => x.Match(label).Success) == null)
            {
                throw ScriptRuntimeException.BadArgument(0, "GetSensorValue", "label is not valid");
            }

            using (var searcher = new ManagementObjectSearcher(@"root\wmi", string.Format("SELECT Value FROM AIDA64_SensorValues WHERE ID='{0}'", label)))
            {
                try
                {
                    var value = searcher.Get().Cast <ManagementBaseObject>().First();

                    try
                    {
                        return(DynValue.NewNumber(Convert.ToDouble(value["Value"])));
                    }
                    catch (FormatException)
                    {
                        // Some values are not supported in trial versions
                        return(DynValue.NewBoolean(false));
                    }
                }
                catch (InvalidOperationException)
                {
                    // Valid label, but may not apply with this hardware (e.g. specific cpu core data)
                    return(DynValue.NewBoolean(false));
                }
                catch (ManagementException e)
                {
                    if (e.ErrorCode == ManagementStatus.InvalidClass)
                    {
                        throw new ScriptRuntimeException("GetSensorValue called but AIDA64 is not running");
                    }
                    else
                    {
                        throw e;
                    }
                }
            }
        }
        /// <summary>
        /// Performs an "index" "set" operation. This tries to resolve minor variations of member names.
        /// </summary>
        /// <param name="script">The script originating the request</param>
        /// <param name="obj">The object (null if a static request is done)</param>
        /// <param name="index">The index.</param>
        /// <param name="value">The value to be set</param>
        /// <param name="isDirectIndexing">If set to true, it's indexed with a name, if false it's indexed through brackets.</param>
        /// <returns></returns>
        public virtual bool SetIndex(Script script, object obj, DynValue index, DynValue value, bool isDirectIndexing)
        {
            if (!isDirectIndexing)
            {
                StandardUserDataOverloadedMethodDescriptor mdesc = m_Methods.GetOrDefault(SPECIAL_SETITEM);

                if (mdesc != null)
                {
                    ExecuteIndexer(mdesc, script, obj, index, value);
                    return(true);
                }
            }

            index = index.ToScalar();

            if (index.Type != DataType.String)
            {
                throw ScriptRuntimeException.BadArgument(1, string.Format("userdata<{0}>.__setindex", this.Name), "string", index.Type.ToLuaTypeString(), false);
            }

            bool v = TrySetIndex(script, obj, index.String, value);

            if (!v)
            {
                v = TrySetIndex(script, obj, UpperFirstLetter(index.String), value);
            }
            if (!v)
            {
                v = TrySetIndex(script, obj, Camelify(index.String), value);
            }
            if (!v)
            {
                v = TrySetIndex(script, obj, UpperFirstLetter(Camelify(index.String)), value);
            }

            return(v);
        }
예제 #13
0
        public static DynValue upvaluejoin(ScriptExecutionContext executionContext, CallbackArguments args)
        {
            var f1 = args.AsType(0, "upvaluejoin", DataType.Function);
            var f2 = args.AsType(2, "upvaluejoin", DataType.Function);
            int n1 = args.AsInt(1, "upvaluejoin") - 1;
            int n2 = args.AsInt(3, "upvaluejoin") - 1;

            var c1 = f1.Function;
            var c2 = f2.Function;

            if (n1 < 0 || n1 >= c1.ClosureContext.Count)
            {
                throw ScriptRuntimeException.BadArgument(1, "upvaluejoin", "invalid upvalue index");
            }

            if (n2 < 0 || n2 >= c2.ClosureContext.Count)
            {
                throw ScriptRuntimeException.BadArgument(3, "upvaluejoin", "invalid upvalue index");
            }

            c2.ClosureContext[n2] = c1.ClosureContext[n1];

            return(DynValue.Void);
        }
예제 #14
0
        public DynValue Index(Script script, object obj, DynValue index)
        {
            if (index.Type != DataType.String)
            {
                throw ScriptRuntimeException.BadArgument(1, string.Format("userdata<{0}>.__index", this.Name), "string", index.Type.ToLuaTypeString(), false);
            }

            DynValue v = TryIndex(script, obj, index.String);

            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, Camelify(index.String));
            }
            if (v == null)
            {
                v = TryIndex(script, obj, UpperFirstLetter(Camelify(index.String)));
            }

            return(v);
        }
예제 #15
0
        public bool SetIndex(Script script, object obj, DynValue index, DynValue value)
        {
            if (index.Type != DataType.String)
            {
                throw ScriptRuntimeException.BadArgument(1, string.Format("userdata<{0}>.__setindex", this.Name), "string", index.Type.ToLuaTypeString(), false);
            }

            bool v = TrySetIndex(script, obj, index.String, value);

            if (!v)
            {
                v = TrySetIndex(script, obj, UpperFirstLetter(index.String), value);
            }
            if (!v)
            {
                v = TrySetIndex(script, obj, Camelify(index.String), value);
            }
            if (!v)
            {
                v = TrySetIndex(script, obj, UpperFirstLetter(Camelify(index.String)), value);
            }

            return(v);
        }
예제 #16
0
        public DynValue HSVtoRGB(double h, double s, double v)
        {
            if (h > 1.0)
            {
                throw ScriptRuntimeException.BadArgument(0, "HSVtoRGB", "range is [0, 1]");
            }

            if (s > 1.0)
            {
                throw ScriptRuntimeException.BadArgument(1, "HSVtoRGB", "range is [0, 1]");
            }

            if (v > 1.0)
            {
                throw ScriptRuntimeException.BadArgument(2, "HSVtoRGB", "range is [0, 1]");
            }

            if (s == 0.0)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(v),
                }));
            }

            var i = Math.Floor(h * 6.0);

            var f = (h * 6.0) - i;
            var p = v * (1.0 - s);
            var q = v * (1.0 - s * f);
            var t = v * (1.0 - s * (1.0 - f));

            i %= 6;

            if (i == 0)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(t),
                    DynValue.NewNumber(p),
                }));
            }

            if (i == 1)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(q),
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(p),
                }));
            }
            else if (i == 2)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(p),
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(t),
                }));
            }
            else if (i == 3)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(p),
                    DynValue.NewNumber(q),
                    DynValue.NewNumber(v),
                }));
            }
            else if (i == 4)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(t),
                    DynValue.NewNumber(p),
                    DynValue.NewNumber(v),
                }));
            }
            else // if (i == 5)
            {
                return(DynValue.NewTuple(new DynValue[]
                {
                    DynValue.NewNumber(v),
                    DynValue.NewNumber(p),
                    DynValue.NewNumber(q),
                }));
            }
        }
예제 #17
0
 protected static void LuaLArgError(LuaState L, lua_Integer arg, string p)
 {
     throw ScriptRuntimeException.BadArgument(arg - 1, L.FunctionName, p);
 }
예제 #18
0
        private void formLoader_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(_G.path))
            {
                Directory.CreateDirectory(_G.path);
            }
            _G.LuaState.Globals["MsgC"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                List <dynamic> args = new List <dynamic>();
                Closure isColor     = (Closure)context.CurrentGlobalEnv["IsColor"];
                for (int i = 0; i < arguments.Count; i++)
                {
                    DynValue arg = arguments.RawGet(i, true);
                    if (arg == DynValue.Nil)
                    {
                        continue;
                    }
                    if (arg.Type == DataType.String)
                    {
                        args.Add(arg.String);
                    }
                    else if (isColor.Call(arg).CastToBool())
                    {
                        Table color = arg.Table;
                        int r       = (int)color.Get("r").Number;
                        int g       = (int)color.Get("g").Number;
                        int b       = (int)color.Get("b").Number;
                        int a       = (int)color.Get("a").Number;
                        args.Add(Color.FromArgb(a, r, g, b));
                    }
                    else
                    {
                        throw ScriptRuntimeException.BadArgument(i, "MsgC", "expected color or string");
                    }
                }
                Util.MsgC(this, args.ToArray());
                return(DynValue.Nil);
            });

            _G.LuaState.Globals["Msg"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                List <dynamic> args = new List <dynamic>();
                for (int i = 0; i < arguments.Count; i++)
                {
                    DynValue arg = arguments.RawGet(i, true);
                    if (arg == DynValue.Nil)
                    {
                        continue;
                    }
                    args.Add(arg);
                }
                Util.MsgC(this, args + "\r\n");
                return(DynValue.Nil);
            });

            _G.LuaState.Options.DebugPrint = s => {
                console.AppendText(s + "\r\n");
            };

            for (int i = 0; i < 10; i++)
            {
                _G.LuaState.Globals[$"clear_{_G.RandomString()}"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                    throw new ScriptRuntimeException("Attempted to clear console.");
                });
            }

            _G.LuaState.Globals[$"clear_{_G.GetSessionID()}"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                console.Clear();
                Util.MsgC(this, Script.GetBanner("Goose Lua"));
                return(DynValue.Nil);
            });

            for (int i = 0; i < 10; i++)
            {
                _G.LuaState.Globals[$"clear_{_G.RandomString()}"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                    throw new ScriptRuntimeException("Attempted to clear console.");
                });
            }

            queue($"concommand.Add(\"clear\", function() clear_{_G.GetSessionID()}() end)", "formLoader");

            _G.LuaState.Globals["AddConsoleCommand"] = new CallbackFunction((ScriptExecutionContext context, CallbackArguments arguments) => {
                string name = arguments.AsStringUsingMeta(context, 0, "AddConsoleCommand");
                commands.Add(name);
                return(DynValue.Nil);
            });

            commands.AddRange(new string[] {
                "help",
                "lua_run_cl"
            });

            string[] files = Directory.GetFiles(_G.path, "*.lua");
            foreach (string mod in files)
            {
                string modFile = Path.GetFileNameWithoutExtension(mod);
                modList.Items.Add(modFile);
                try {
                    string code = File.ReadAllText(mod);
                    queue(code, modFile);
                } catch (ScriptRuntimeException ex) {
                    Util.MsgC(this, Color.FromArgb(255, 0, 0), string.Format("Doh! An error occured! {0}", ex.DecoratedMessage), "\r\n");
                }
            }
        }
예제 #19
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()));
            }
        }