Beispiel #1
0
        public void Test_ListMethod(InteropAccessMode opt)
        {
            UserData.UnregisterType <SomeClass>();

            string script = @"    
				x = mklist(1, 4);
				sum = 0;				

				for _, v in ipairs(x) do
					sum = sum + v;
				end

				return sum;"                ;

            Script S = new Script();

            SomeClass obj = new SomeClass();

            S.Globals["mklist"] = CallbackFunction.FromDelegate(S, (Func <int, int, List <int> >)obj.MkList, opt);

            DynValue res = S.DoString(script);

            Assert.AreEqual(DataType.Number, res.Type);
            Assert.AreEqual(10, res.Number);
        }
Beispiel #2
0
        public void testTail()
        {
            var lua = @"    
                print(tail)
                tail(100)
            ";

            //var script = new Script();
            script.Globals["tail"] = DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Func <int, DynValue>)newTail));
            script.DoString(lua);

            Console.ReadKey();
        }
        public void Test_DelegateMethod(InteropAccessMode opt)
        {
            UserData.UnregisterType <SomeClass>();

            string script = @"    
				x = concat(1, 2);
				return x;"                ;

            Script S = new Script();

            SomeClass obj = new SomeClass();

            S.Globals["concat"] = CallbackFunction.FromDelegate(S, (Func <int, int, string>)obj.ConcatNums, opt);

            DynValue res = S.DoString(script);

            Assert.AreEqual(DataType.String, res.Type);
            Assert.AreEqual("1%2", res.String);
        }
Beispiel #4
0
        /// <summary>
        /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis
        /// </summary>
        internal static R_VAL ObjectToValue(RubyState state, object obj)
        {
            R_VAL v = TryObjectToSimpleValue(script, obj);

            if (v != null)
            {
                return(v);
            }

            v = UserData.Create(obj);
            if (v != null)
            {
                return(v);
            }

            if (obj is Type)
            {
                v = UserData.CreateStatic(obj as Type);
            }

            // unregistered enums go as integers
            if (obj is Enum)
            {
                return(R_VAL.NewNumber(
                           NumericConversions.TypeToDouble(Enum.GetUnderlyingType(obj.GetType()), obj)));
            }

            if (v != null)
            {
                return(v);
            }

            if (obj is Delegate)
            {
                return(R_VAL.NewCallback(CallbackFunction.FromDelegate(script, ( Delegate )obj)));
            }

            if (obj is MethodInfo)
            {
                MethodInfo mi = ( MethodInfo )obj;

                if (mi.IsStatic)
                {
                    return(R_VAL.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }

            if (obj is System.Collections.IList)
            {
                Table t = TableConversions.ConvertIListToTable(script, (System.Collections.IList)obj);
                return(R_VAL.NewTable(t));
            }

            if (obj is System.Collections.IDictionary)
            {
                Table t = TableConversions.ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj);
                return(R_VAL.NewTable(t));
            }

            var enumerator = EnumerationToValue(script, obj);

            if (enumerator != null)
            {
                return(enumerator);
            }


            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }
        /// <summary>
        /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis
        /// </summary>
        internal static DynValue ObjectToDynValue(Script script, object obj)
        {
            var v = TryObjectToSimpleDynValue(script, obj);

            if (v != null)
            {
                return(v);
            }

            v = UserData.Create(obj);
            if (v != null)
            {
                return(v);
            }

            if (obj is Type type)
            {
                v = UserData.CreateStatic(type);
            }

            // unregistered enums go as integers
            if (obj is Enum)
            {
                return(DynValue.NewNumber(NumericConversions.TypeToDouble(Enum.GetUnderlyingType(obj.GetType()), obj)));
            }

            if (v != null)
            {
                return(v);
            }

            if (obj is Delegate d)
            {
                return(DynValue.NewCallback(CallbackFunction.FromDelegate(script, d)));
            }

            if (obj is MethodInfo mi)
            {
                if (mi.IsStatic)
                {
                    return(DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }

            if (obj is IList list)
            {
                var t = TableConversions.ConvertIListToTable(script, list);
                return(DynValue.NewTable(t));
            }

            if (obj is IDictionary dict)
            {
                var t = TableConversions.ConvertIDictionaryToTable(script, dict);
                return(DynValue.NewTable(t));
            }

            var enumerator = EnumerationToDynValue(script, obj);

            if (enumerator != null)
            {
                return(enumerator);
            }


            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }
        internal static DynValue ClrObjectToComplexMoonSharpValue(Script script, object obj)
        {
            DynValue v = TryClrObjectToSimpleMoonSharpValue(script, obj);

            if (v != null)
            {
                return(v);
            }

            v = UserData.Create(obj);

            if (v != null)
            {
                return(v);
            }

            if (obj is Type)
            {
                v = UserData.CreateStatic(obj as Type);
            }

            if (v != null)
            {
                return(v);
            }

            if (obj is Delegate)
            {
                return(DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Delegate)obj)));
            }

            if (obj is MethodInfo)
            {
                MethodInfo mi = (MethodInfo)obj;

                if (mi.IsStatic)
                {
                    return(DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }


            if (obj is System.Collections.IList)
            {
                Table t = ConvertIListToTable(script, (System.Collections.IList)obj);
                return(DynValue.NewTable(t));
            }

            if (obj is System.Collections.IDictionary)
            {
                Table t = ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj);
                return(DynValue.NewTable(t));
            }

            if (obj is System.Collections.IEnumerable)
            {
                var enumer = (System.Collections.IEnumerable)obj;
                return(EnumerableWrapper.ConvertIterator(script, enumer.GetEnumerator()));
            }

            if (obj is System.Collections.IEnumerator)
            {
                var enumer = (System.Collections.IEnumerator)obj;
                return(EnumerableWrapper.ConvertIterator(script, enumer));
            }

            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }
        /// <summary>
        /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis
        /// </summary>
        internal static DynValue ObjectToDynValue(Script script, object obj)
        {
            if (obj == null)
            {
                return(DynValue.Nil);
            }
            if (obj is DynValue _dyn)
            {
                return(_dyn);
            }
            if (obj is Task task)
            {
                return(ObjectToDynValue(script, new TaskWrapper(task)));
            }

            DynValue v = TryObjectToSimpleDynValue(script, obj);

            if (v.IsNotNil())
            {
                return(v);
            }

            v = UserData.Create(obj);
            if (v.IsNotNil())
            {
                return(v);
            }

            if (obj is Type)
            {
                v = UserData.CreateStatic(obj as Type);
            }

            // unregistered enums go as integers
            if (obj is Enum)
            {
                return(DynValue.NewNumber(NumericConversions.TypeToDouble(Enum.GetUnderlyingType(obj.GetType()), obj)));
            }

            if (v.IsNotNil())
            {
                return(v);
            }

            if (obj is Delegate)
            {
                return(DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Delegate)obj)));
            }

            if (obj is MethodInfo)
            {
                MethodInfo mi = (MethodInfo)obj;

                if (mi.IsStatic)
                {
                    return(DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }

            if (obj is System.Collections.IList)
            {
                Table t = TableConversions.ConvertIListToTable(script, (System.Collections.IList)obj);
                return(DynValue.NewTable(t));
            }

            if (obj is System.Collections.IDictionary)
            {
                Table t = TableConversions.ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj);
                return(DynValue.NewTable(t));
            }

            var enumerator = EnumerationToDynValue(script, obj);

            if (enumerator.IsNotNil())
            {
                return(enumerator);
            }


            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }
Beispiel #8
0
        public override void OnEnable()
        {
            //Register user data type;
            UserData.RegisterType <UnityEngine.GameObject>();
            UserData.RegisterType <Smod2.API.UserGroup>();
            UserData.RegisterType <Smod2.API.Item>();
            UserData.RegisterType <TeamRole>();
            UserData.RegisterType <Connection>();
            UserData.RegisterType <Server>();
            UserData.RegisterType <Map>();
            UserData.RegisterType <Door>();
            UserData.RegisterType <Elevator>();
            UserData.RegisterType <Round>();
            UserData.RegisterType <RoundStats>();
            UserData.RegisterType <Vector>();
            UserData.RegisterType <PocketDimensionExit>();
            UserData.RegisterType <TeslaGate>();
            UserData.RegisterType <Scp914.Recipe>();
            UserData.RegisterType <Modules.Timer>();
            UserData.RegisterType <Modules.Timer.TimerInstance>();
            UserData.RegisterType <Modules.File>();
            UserData.RegisterType <Functions.Player>();
            UserData.RegisterType <Functions.Warhead>();
            UserData.RegisterType <Functions.SCP914>();
            UserData.RegisterType <Modules.MySQL>();
            UserData.RegisterType <Modules.MySQLConnection>();
            UserData.RegisterType <Modules.MySQLQuery>();
            UserData.RegisterType <Modules.LuaSocket.LuaWrapper>();
            UserData.RegisterType <Modules.LuaSocket.qLuaPacket>();
            UserData.RegisterType <Modules.LuaSocket.qConnection>();
            UserData.RegisterType <Role>();
            UserData.RegisterType <Team>();
            UserData.RegisterType <UserRank>();
            UserData.RegisterType <ItemType>();
            UserData.RegisterType <AmmoType>();
            UserData.RegisterType <DamageType>();
            UserData.RegisterType <ElevatorStatus>();
            UserData.RegisterType <ElevatorType>();
            UserData.RegisterType <IntercomStatus>();
            UserData.RegisterType <KnobSetting>();
            UserData.RegisterType <PocketDimensionExitType>();
            UserData.RegisterType <RadioStatus>();
            UserData.RegisterType <ROUND_END_STATUS>();
            //Register classes;
            Hooks hooks = new Hooks(this);

            Functions.SCP914 scp914 = new Functions.SCP914(this);
            //Register events;

#if !DEBUG
            this.AddEventHandler(typeof(IEventHandlerRoundStart), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerCheckRoundEnd), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerRoundEnd), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerConnect), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerDisconnect), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerWaitingForPlayers), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerRoundRestart), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerUpdate), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerFixedUpdate), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerCheckEscape), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerJoin), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerSpawn), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerTeamRespawn), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerSpawnRagdoll), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerCheckEscape), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerSetRole), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerHurt), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerDie), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerPickupItem), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerPickupItemLate), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPlayerDropItem), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerMedkitUse), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerLure), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerRadioSwitch), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerShoot), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerThrowGrenade), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandler106CreatePortal), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandler106Teleport), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerContain106), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPocketDimensionEnter), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPocketDimensionExit), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerPocketDimensionDie), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerIntercom), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerWarheadStartCountdown), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerWarheadStopCountdown), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerWarheadDetonate), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerLCZDecontaminate), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerAdminQuery), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerAuthCheck), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerBan), hooks, Priority.Highest);
            this.AddEventHandler(typeof(IEventHandlerSCP914Activate), scp914, Priority.Highest);
#endif
            try
            {
                string luaPath = Directory.GetCurrentDirectory() + "/lua";
#if DEBUG
                lua = new Script(CoreModules.Preset_Complete);
#else
                lua = new Script();
#endif

                UserData.RegisterType <Player>(new DynamicIndex(lua, typeof(Player), typeof(Functions.PlayerExtension)));


                wrappedMeta = lua.DoString(@"
				return { __index = function(t, name) 
                local obj = rawget(t, '_object'); if (obj) then return obj[name]; end 
                local meta = rawget(t, '_base');  if (meta) then return meta[name]; end
                end } ").Table;

                //Register lua globals;
                //ne //lua.Globals["file"] = new Modules.File(dir + "/");
                lua.Globals["timer"] = Modules.Timer.singleton;
                // lua.Globals["hook"] = hooks;
                lua.Globals["mysql"]  = new Modules.MySQL(this);
                lua.Globals["socket"] = new Modules.LuaSocket.LuaWrapper(this);
                Dictionary <string, object> StaticResource = new Dictionary <string, object>();
                StaticResource.Add("Role", UserData.CreateStatic <Role>());
                StaticResource.Add("Item", UserData.CreateStatic <ItemType>());
                StaticResource.Add("Ammo", UserData.CreateStatic <AmmoType>());
                StaticResource.Add("DamageType", UserData.CreateStatic <DamageType>());
                StaticResource.Add("ElevatorStatus", UserData.CreateStatic <ElevatorStatus>());
                StaticResource.Add("ElevatorType", UserData.CreateStatic <ElevatorType>());
                StaticResource.Add("IntercomStatus", UserData.CreateStatic <IntercomStatus>());
                StaticResource.Add("KnobSetting", UserData.CreateStatic <KnobSetting>());
                StaticResource.Add("PocketDimensionExitType", UserData.CreateStatic <PocketDimensionExitType>());
                StaticResource.Add("RadioStatus", UserData.CreateStatic <RadioStatus>());
                StaticResource.Add("RoundEndStatus", UserData.CreateStatic <ROUND_END_STATUS>());
                StaticResource.Add("Team", UserData.CreateStatic <Smod2.API.Team>());
                StaticResource.Add("UserRank", UserData.CreateStatic <UserRank>());
                lua.Globals["static"]  = StaticResource;
                lua.Globals["player"]  = new Functions.Player();
                lua.Globals["warhead"] = new Functions.Warhead();
                lua.Globals["scp914"]  = scp914;

                List <string> cvars = new List <string>();
                Table         con   = new Table(lua);
                con["RegString"] = new Action <string, string>((key, def) => {
                    if (cvars.Contains(key))
                    {
                        return;
                    }
                    AddConfig(new Smod2.Config.ConfigSetting(key, (def != null) ? def : "default", Smod2.Config.SettingType.STRING, true, "qlay-variable"));
                    cvars.Add(key);
                });
                con["GetString"]      = CallbackFunction.FromDelegate(lua, new Func <string, string>(GetConfigString));
                con["GetNumber"]      = CallbackFunction.FromDelegate(lua, new Func <string, float>(GetConfigFloat));
                con["GetBool"]        = CallbackFunction.FromDelegate(lua, new Func <string, bool>(GetConfigBool));
                lua.Globals["ConVar"] = con;



                luaHookCall = lua.DoString(Modules.StaticLua.LuaHook, null, "Hook system");
                lua.DoString(Modules.StaticLua.TableExtension, null, "Table extension");
                lua.DoString(Modules.StaticLua.DBModel, null, "DataBase Model");

                //file refresh
#if !DEBUG
                watcher = new FileSystemWatcher(luaPath + "/", "*.lua");
                //watcher.Filter = "*.*";
                watcher.NotifyFilter          = NotifyFilters.LastWrite;
                watcher.Changed              += OnFileChanged;
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents   = true;
#endif


                //load plugins

                if (Directory.Exists(luaPath))
                {
                    foreach (string dir in Directory.GetDirectories(luaPath, "*", SearchOption.TopDirectoryOnly))
                    {
                        var   g        = lua.Globals;
                        Table localEnv = new Table(lua);
                        foreach (var item in g.Keys)
                        {
                            localEnv[item] = g[item];
                        }
                        localEnv["file"]    = new Modules.File(dir + "/");
                        localEnv["include"] = new Action <string>((file) =>
                        {
                            LoadPluginFile(dir, localEnv, file);
                        });
                        localEnv["require"] = null;
                        //Info("env created ");


                        LoadPluginFile(dir, localEnv);
                        //Info("file loaded ");

                        Table  pluginInfo = localEnv.Get("pluginInfo").ToObject <Table>();
                        string id         = pluginInfo.Get("id").String;
                        string name       = pluginInfo.Get("name").String;
                        string author     = pluginInfo.Get("author").String;
                        string version    = pluginInfo.Get("version").String;
                        //lua.Options.DebugPrint = s => { Info( "[" + id + "] " + s); };
                        lua.Options.DebugPrint = s => { Info("[LUA] " + s); };
                        log.Info("qlay->LUA", name + "(ver:" + version + ") by " + author + " has loaded");

                        localEnv["MsgN"] = new Action <string>((message) => {
                            log.Info(id, message);
                            luaHookCall.Function.Call("OnLog", "[" + id + "] " + message);
                        });

                        if (localEnv["Init"] != null)
                        {
                            lua.Call(localEnv["Init"]);
                        }
                        //Info("init called ");

                        LuaPlugin plugin = new LuaPlugin(dir);
                        plugin.id      = id;
                        plugin.context = localEnv;
                        PluginList.Add(plugin);
                        //Info("plugin added");
                    }
                }
                else
                {
                    Directory.CreateDirectory(luaPath);
                }
            }
            catch (InterpreterException ex)
            {
                log.Error("qlay", "Lua error: " + ex.DecoratedMessage);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis
        /// </summary>
        internal static DynValue ObjectToDynValue(Script script, object obj)
        {
            DynValue v = TryObjectToSimpleDynValue(script, obj);

            if (v != null)
            {
                return(v);
            }

            v = UserData.Create(obj);

            if (v != null)
            {
                return(v);
            }

            if (obj is Type)
            {
                v = UserData.CreateStatic(obj as Type);
            }

            if (v != null)
            {
                return(v);
            }

            if (obj is Delegate)
            {
                return(DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Delegate)obj)));
            }

            if (obj is MethodInfo)
            {
                MethodInfo mi = (MethodInfo)obj;

                if (mi.IsStatic)
                {
                    return(DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }

            if (obj is System.Collections.IList)
            {
                Table t = TableConversions.ConvertIListToTable(script, (System.Collections.IList)obj);
                return(DynValue.NewTable(t));
            }

            if (obj is System.Collections.IDictionary)
            {
                Table t = TableConversions.ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj);
                return(DynValue.NewTable(t));
            }

            var enumerator = EnumerationToDynValue(script, obj);

            if (enumerator != null)
            {
                return(enumerator);
            }


            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }
Beispiel #10
0
        /// <summary>
        /// Tries to convert a CLR object to a MoonSharp value, using more in-depth analysis
        /// </summary>
        internal static DynValue ObjectToDynValue(Script script, object obj)
        {
            DynValue v = TryObjectToSimpleDynValue(script, obj);

            if (v != null)
            {
                return(v);
            }

            v = UserData.Create(obj);
            if (v != null)
            {
                return(v);
            }

            if (obj is Type)
            {
                v = UserData.CreateStatic(obj as Type);
            }

            // unregistered enums go as integers
            if (obj is Enum)
            {
                return(DynValue.NewNumber(NumericConversions.TypeToDouble(Enum.GetUnderlyingType(obj.GetType()), obj)));
            }

            if (v != null)
            {
                return(v);
            }

            if (obj is Delegate)
            {
                return(DynValue.NewCallback(CallbackFunction.FromDelegate(script, (Delegate)obj)));
            }

            if (obj is MethodInfo)
            {
                MethodInfo mi = (MethodInfo)obj;

                if (mi.IsStatic)
                {
                    return(DynValue.NewCallback(CallbackFunction.FromMethodInfo(script, mi)));
                }
            }

            if (obj is System.Collections.IList)
            {
                Table t = TableConversions.ConvertIListToTable(script, (System.Collections.IList)obj);
                return(DynValue.NewTable(t));
            }

            if (obj is System.Collections.IDictionary)
            {
                Table t = TableConversions.ConvertIDictionaryToTable(script, (System.Collections.IDictionary)obj);
                return(DynValue.NewTable(t));
            }

#if HASDYNAMIC
            var objType = obj.GetType();

#if PCL
            var isTuple = objType.IsGenericType && objType.GetInterfaces().Where(f => f.Name == "ITuple").Count() > 0;
#else
            var isTuple = objType.IsGenericType && objType.GetInterface("ITuple") != null;
#endif

            if (isTuple)
            {
                var args = objType.GetGenericArguments().Length;
                var vals = new DynValue[args];

                for (int i = 0; i < args; i++)
                {
                    var prop = objType.GetProperty("Item" + (i + 1));
                    var val  = prop.GetValue(obj, null);
                    vals[i] = DynValue.FromObject(script, val);
                }

                return(DynValue.NewTupleNested(vals));
            }
#endif

            var enumerator = EnumerationToDynValue(script, obj);
            if (enumerator != null)
            {
                return(enumerator);
            }


            throw ScriptRuntimeException.ConvertObjectFailed(obj);
        }