コード例 #1
1
ファイル: LuaExtension.cs プロジェクト: RuanPitout88/Oxide
        /// <summary>
        /// Initializes the Lua environment
        /// </summary>
        private void InitializeLua()
        {
            // Create the Lua environment
            LuaEnvironment = new NLua.Lua();

            // Filter useless or potentially malicious libraries/functions
            LuaEnvironment["os"] = null;
            LuaEnvironment["io"] = null;
            LuaEnvironment["require"] = null;
            LuaEnvironment["dofile"] = null;
            LuaEnvironment["package"] = null;
            LuaEnvironment["luanet"] = null;
            LuaEnvironment["load"] = null;

            // Read util methods
            setmetatable = LuaEnvironment["setmetatable"] as LuaFunction;

            // Create metatables
            //Type mytype = GetType();
            LuaEnvironment.NewTable("tmp");
            overloadselectormeta = LuaEnvironment["tmp"] as LuaTable;
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("FindOverload", BindingFlags.Public | BindingFlags.Static));
            LuaEnvironment.NewTable("tmp");
            // Ideally I'd like for this to be implemented C# side, but using C#-bound methods as metamethods seems dodgy
            LuaEnvironment.LoadString(
            @"function tmp:__index( key )
            local sftbl = rawget( self, '_sftbl' )
            local field = sftbl[ key ]
            if (field) then return field:GetValue( nil ) end
            end
            function tmp:__newindex( key, value )
            local sftbl = rawget( self, '_sftbl' )
            local field = sftbl[ key ]
            if (field) then field:SetValue( nil, value ) end
            end
            ", "LuaExtension").Call();
            //LuaEnvironment.RegisterFunction("tmp.__index", mytype.GetMethod("ReadStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            //LuaEnvironment.RegisterFunction("tmp.__newindex", mytype.GetMethod("WriteStaticProperty", BindingFlags.NonPublic | BindingFlags.Static));
            typetablemeta = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("tmp");
            LuaEnvironment.LoadString(
            @"function tmp:__index( key )
            if (type( key ) == 'table') then
            local baseType = rawget( self, '_type' )
            return util.SpecializeType( baseType, key )
            end
            end
            ", "LuaExtension").Call();
            generictypetablemeta = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment["tmp"] = null;

            LuaEnvironment.NewTable("libraryMetaTable");
            LuaEnvironment.LoadString(
            @"function libraryMetaTable:__index( key )
            local ptbl = rawget( self, '_properties' )
            local property = ptbl[ key ]
            if (property) then return property:GetValue( rawget( self, '_object' ), null ) end
            end
            function libraryMetaTable:__newindex( key, value )
            local ptbl = rawget( self, '_properties' )
            local property = ptbl[ key ]
            if (property) then property:SetValue( rawget( self, '_object' ), value ) end
            end
            ", "LuaExtension").Call();
            libraryMetaTable = LuaEnvironment["libraryMetaTable"] as LuaTable;
            LuaEnvironment["libraryMetaTable"] = null;

            LuaEnvironment.NewTable("tmp");
            PluginMetatable = LuaEnvironment["tmp"] as LuaTable;
            LuaEnvironment.LoadString(
            @"function tmp:__newindex( key, value )
            if (type( value ) ~= 'function') then return rawset( self, key, value ) end
            local activeAttrib = rawget( self, '_activeAttrib' )
            if (not activeAttrib) then return rawset( self, key, value ) end
            if (activeAttrib == self) then
            print( 'PluginMetatable.__newindex - self._activeAttrib was somehow self!' )
            rawset( self, key, value )
            return
            end
            local attribArr = rawget( self, '_attribArr' )
            if (not attribArr) then
            attribArr = {}
            rawset( self, '_attribArr', attribArr )
            end
            activeAttrib._func = value
            attribArr[#attribArr + 1] = activeAttrib
            rawset( self, '_activeAttrib', nil )
            end
            ", "LuaExtension").Call();
            LuaEnvironment["tmp"] = null;
        }
コード例 #2
0
 public IfElseStatement(LuaFunction checkstate_function)
 {
     conditionCheckFunction = checkstate_function;
     executionBlock = null;
     nextStatement = null;
     executingStatement = null;
 }
コード例 #3
0
ファイル: LuaGame.cs プロジェクト: CallumDev/BubbleEngine
 public LuaGame(string entryPath)
 {
     Window.Title = "Bubble Engine";
     //create lua state
     state = new BubbleLua (new Lua());
     state.Lua.LoadCLRPackage ();
     state.Bubble ["runtime"] = new LuaAPI.Runtime();
     state.Bubble ["fonts"] = new LuaAPI.Fonts (FontContext);
     luaGraphics = new LuaAPI.Graphics (null, this);
     state.Bubble ["graphics"] = luaGraphics;
     state.Bubble ["window"] = new LuaAPI.LWindow (Window);
     LuaAPI.Util.RegisterEnum (typeof(Keys), state);
     state.Lua ["embedres"] = new LuaAPI.EmbeddedLoader ();
     //run init scripts
     state.Lua.DoString(EmbeddedResources.GetString("BubbleEngine.LuaAPI.procure.lua"));
     state.Lua.DoString(EmbeddedResources.GetString("BubbleEngine.LuaAPI.init.lua"));
     //config
     state.Lua.DoFile(entryPath);
     gameTable = (LuaTable)state.Lua ["game"];
     var cfg = (LuaFunction)gameTable ["config"];
     if (cfg == null) {
         throw new NLua.Exceptions.LuaScriptException ("Script must have a game.config() function", entryPath);
     }
     cfg.Call ();
     updateFunction = (LuaFunction)gameTable ["update"];
     drawFunction = (LuaFunction)gameTable ["draw"];
 }
コード例 #4
0
        protected internal override void AddToActor(CompositeActor actor)
        {
            base.AddToActor(actor);

            string functionName = $"checkTransition{Name}";
            conditionFunction = actor.ScriptSystem.LoadString($"return {condition}", functionName);
        }
コード例 #5
0
ファイル: EnemySprite.cs プロジェクト: daxnet/Starwar
 public EnemySprite(Texture2D texture, Vector2 position, float speed)
     : base(texture, position)
 {
     this.speed = speed;
     this.initPos = position;
     state.DoString(Script);
     luaFunction = state["CalculatePosition"] as LuaFunction;
 }
コード例 #6
0
 public static void SetPath(string v_path)
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("setPath");
     if (fun != null)
     {
         fun.Call(v_path);
     }
 }
コード例 #7
0
        protected override void PreStart()
        {
            base.PreStart();

            ScriptSystem["args"] = args;

            ScriptSystem.RegisterFunction("createMessage", this.GetType().GetMethod(nameof(CreateMessage)));
            ScriptSystem.RegisterFunction("putMessage", this, this.GetType().GetMethod(nameof(PutMessage)));

            execution = ScriptSystem.LoadString(script, "execute");
        }
コード例 #8
0
 public TwitterPost()
 {
     //シングルトンだし...まぁ多少はね?
     if (lua != null && luaFunc != null) return;
     //Luaのファイルをとりあえず走らせちゃう
     lua.LoadCLRPackage();
     lua.RegisterFunction("console", typeof(Trace).GetMethod("WriteLine", new Type[] { typeof(string)}));
     lua.DoFile(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\Lua\tweet.lua");
     //ツイート時のfunctionを取得
     lua.GetFunction("main").Call();
     luaFunc = lua.GetFunction("OnTweet");
 }
コード例 #9
0
 public static void DoMain()
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("main");
     try
     {
         fun.Call();
     }
     catch (Exception ex)
     {
         Debug.Exception("执行main报错,信息是" + ex.ToString());
     }
 }
コード例 #10
0
    /// <summary>
    /// 执行Lua方法
    /// </summary>
    protected object[] CallMethod(string func, GameObject go)
    {
        if (nluaMgr == null)
        {
            return(null);
        }
        string funcName = name + "." + func;

        funcName = funcName.Replace("(Clone)", "");
        NLua.LuaFunction luafunc = nmgr.GetFunction(funcName);
        if (luafunc == null)
        {
            return(null);
        }
        else
        {
            return(luafunc.Call(funcName));
        }
    }
コード例 #11
0
 public static ClientChatLineDelegate MakeDelegate(LuaFunction lua)
 {
     return((int groupId, ref string message, ref EnumHandling handled) => {
         lua.Call(groupId, message, handled);
     });
 }
コード例 #12
0
ファイル: Main.cs プロジェクト: khwoo1004/Oxide
 private bool lua_SendWebRequest(string url, LuaFunction func)
 {
     if (webrequests.Count > 3)
     {
         return false;
     }
     AsyncWebRequest req = new AsyncWebRequest(url);
     webrequests.Add(req);
     Plugin callerplugin = Plugin.CurrentPlugin;
     req.OnResponse += (r) =>
     {
         try
         {
             func.Call(r.ResponseCode, r.Response);
         }
         catch (Exception ex)
         {
             //Debug.LogError(string.Format("Error in webrequest callback: {0}", ex));
             Logger.Error(string.Format("Error in webrequest callback ({0})", callerplugin), ex);
         }
     };
     return true;
 }
コード例 #13
0
 public void RegisterHook(string name, LuaFunction function)
 {
     Console.WriteLine("\t Hook Registered: " + name);
     hooks[name] = function;
 }
コード例 #14
0
ファイル: ScriptEngine.cs プロジェクト: mMellowz/revcore
 public void Event()
 {
     this.UseItemEvent = Lua.GetFunction("UseItmeTrigGer");
     this.OpenItemEvent = Lua.GetFunction("OpenItmeTrigGer");
     this.MonsterDeadEvent = Lua.GetFunction("DestroyMonster");
 }
コード例 #15
0
ファイル: LuaPlugin.cs プロジェクト: RuanPitout88/Oxide
        /// <summary>
        /// Handles a method attribute
        /// </summary>
        /// <param name="name"></param>
        /// <param name="method"></param>
        /// <param name="data"></param>
        private void HandleAttribute(string name, LuaFunction method, LuaTable data)
        {
            // What type of attribute is it?
            switch (name)
            {
                case "Command":
                    // Parse data out of it
                    List<string> cmdNames = new List<string>();
                    int i = 0;
                    while (data[++i] != null) cmdNames.Add(data[i] as string);
                    string[] cmdNamesArr = cmdNames.Where((s) => !string.IsNullOrEmpty(s)).ToArray();
                    string[] cmdPermsArr;
                    if (data["permission"] is string)
                    {
                        cmdPermsArr = new string[] { data["permission"] as string };
                    }
                    else if (data["permission"] is LuaTable || data["permissions"] is LuaTable)
                    {
                        LuaTable permsTable = (data["permission"] as LuaTable) ?? (data["permissions"] as LuaTable);
                        List<string> cmdPerms = new List<string>();
                        i = 0;
                        while (permsTable[++i] != null) cmdPerms.Add(permsTable[i] as string);
                        cmdPermsArr = cmdPerms.Where((s) => !string.IsNullOrEmpty(s)).ToArray();
                    }
                    else
                        cmdPermsArr = new string[0];

                    // Register it
                    AddCovalenceCommand(cmdNamesArr, cmdPermsArr, (cmd, type, caller, args) =>
                    {
                        HandleCommandCallback(method, cmd, type, caller, args);
                        return true;
                    });

                    break;
            }
        }
コード例 #16
0
ファイル: CozyLuaFunction.cs プロジェクト: xxy1991/cozy
 public CozyLuaFunction(LuaFunction func)
 {
     mFunc = func;
 }
コード例 #17
0
ファイル: LuaBehaviour.cs プロジェクト: fankidark/ME_NLua
 //延迟执行
 public void LuaInvoke(float delaytime,LuaFunction func,params object[] args)
 {
     StartCoroutine(doInvoke(delaytime, func, args));
 }
コード例 #18
0
ファイル: LuaBehaviour.cs プロジェクト: fankidark/ME_NLua
 private IEnumerator doCoroutine(YieldInstruction ins, LuaFunction func, params object[] args)
 {
     yield return ins;
     if (args != null)
     {
         func.Call(args);
     }
     else
     {
         func.Call();
     }
 }
コード例 #19
0
ファイル: Actor.cs プロジェクト: TODOTomorrow/Simple
 public void on(string eventName, LuaFunction func)
 {
     if (!luaEvents.ContainsKey(eventName))
         luaEvents[eventName.ToLower().Trim()] = new List<LuaFunction>();
     luaEvents[eventName.ToLower().Trim()].Add(func);
 }
コード例 #20
0
ファイル: Plugin.cs プロジェクト: rockerdsk/Oxide
        private object CallFunction(LuaFunction func, object[] args)
        {
            // Check the method is loaded
            if (LuaCallFunction == null) LuaCallFunction = typeof(Lua).GetMethod("CallFunction", BindingFlags.NonPublic | BindingFlags.Instance, null, LuaCallFunctionSig, null);

            // Setup args
            LuaCallFunctionArgs[0] = func;
            LuaCallFunctionArgs[1] = args;
            LuaCallFunctionArgs[2] = null;

            // Call it
            return LuaCallFunction.Invoke(LuaInstance, LuaCallFunctionArgs);
        }
コード例 #21
0
ファイル: LeanTween.cs プロジェクト: fankidark/ME_NLua
 public LTDescr setOnComplete(LuaFunction onComplete)
 {
     this.onLuaComplete = onComplete;
     return this;
 }
コード例 #22
0
ファイル: LeanTween.cs プロジェクト: fankidark/ME_NLua
    public static int delayedCall(GameObject gameObject, float delayTime, LuaFunction callback, Hashtable optional)
    {
        if (optional == null)
        optional = new Hashtable();
        optional["onComplete"] = callback;

        return pushNewTween(gameObject, Vector3.zero, delayTime, TweenAction.CALLBACK, optional);
    }
コード例 #23
0
ファイル: LeanTween.cs プロジェクト: fankidark/ME_NLua
 public static int delayedCall(float delayTime, LuaFunction callback, object[] optional)
 {
     init();
     return delayedCall(tweenEmpty, delayTime, callback, h(optional));
 }
コード例 #24
0
ファイル: LeanTween.cs プロジェクト: fankidark/ME_NLua
 public static int delayedCall(float delayTime, LuaFunction callback, Hashtable optional)
 {
     init();
     return delayedCall(tweenEmpty, delayTime, callback, optional);
 }
コード例 #25
0
ファイル: LuaPlugin.cs プロジェクト: RuanPitout88/Oxide
 private void HandleCommandCallback(LuaFunction func, string cmd, CommandType type, IPlayer caller, string[] args)
 {
     LuaEnvironment.NewTable("tmp");
     LuaTable argsTable = LuaEnvironment["tmp"] as LuaTable;
     LuaEnvironment["tmp"] = null;
     for (int i = 0; i < args.Length; i++)
     {
         argsTable[i + 1] = args[i];
     }
     try
     {
         func.Call(Table, caller, argsTable);
     }
     catch (Exception)
     {
         // TODO: Error handling and stuff
         throw;
     }
 }
コード例 #26
0
ファイル: Event.cs プロジェクト: spi8823/Sudenona
        public LuaCoroutine(Lua l)
        {
            lua = l;
            string source = Resources.Load<TextAsset>("LuaSources/Coroutine.lua").text;
            lua.DoString(source);

            startFunction = lua.GetFunction("StartCoroutines");
            updateFunction = lua.GetFunction("UpdateCoroutines");
        }
コード例 #27
0
ファイル: CodeGeneration.cs プロジェクト: CartBlanche/NLua
        /*
         * Gets a delegate with delegateType that calls the luaFunc Lua function
         * Caches the generated type.
         */
        public Delegate GetDelegate(Type delegateType, LuaFunction luaFunc)
        {
            var returnTypes = new List<Type> ();
            Type luaDelegateType;

            if (delegateCollection.ContainsKey (delegateType))
                luaDelegateType = delegateCollection [delegateType];
            else {
                luaDelegateType = GenerateDelegate (delegateType);
                delegateCollection [delegateType] = luaDelegateType;
            }

            var methodInfo = delegateType.GetMethod ("Invoke");
            returnTypes.Add (methodInfo.ReturnType);

            foreach (ParameterInfo paramInfo in methodInfo.GetParameters()) {
                if (paramInfo.ParameterType.IsByRef)
                    returnTypes.Add (paramInfo.ParameterType);
            }

            var luaDelegate = (LuaDelegate)Activator.CreateInstance (luaDelegateType);
            luaDelegate.function = luaFunc;
            luaDelegate.returnTypes = returnTypes.ToArray ();

            return Delegate.CreateDelegate (delegateType, luaDelegate, "CallFunction");
        }
コード例 #28
0
ファイル: LuaBehaviour.cs プロジェクト: fankidark/ME_NLua
 //协程
 public void RunCoroutine(YieldInstruction ins, LuaFunction func, params object[] args)
 {
     StartCoroutine(doCoroutine(ins, func, args));
 }
コード例 #29
0
 /*
  * Gets an event handler for the event type that delegates to the eventHandler Lua function.
  * Caches the generated type.
  */
 public LuaEventHandler GetEvent(Type eventHandlerType, LuaFunction eventHandler)
 {
     throw new NotImplementedException(" Emit not available on Unity ");
 }
コード例 #30
0
ファイル: LuaBehaviour.cs プロジェクト: fankidark/ME_NLua
 private IEnumerator doInvoke(float delaytime, LuaFunction func, params object[] args)
 {
     yield return new  WaitForSeconds(delaytime);
     if (args != null)
     {
         func.Call(args);
     }
     else
     {
         func.Call();
     }
 }
コード例 #31
0
 public static void DoMain()
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("main");
     fun.Call();
 }
コード例 #32
0
ファイル: Main.cs プロジェクト: khwoo1004/Oxide
 private Timer lua_NewTimer(float delay, int numiterations, LuaFunction func)
 {
     Plugin callerplugin = Plugin.CurrentPlugin;
     Action callback = new Action(() =>
     {
         try
         {
             func.Call();
         }
         catch (Exception ex)
         {
             //Logger.Error(string.Format("Error in timer ({1}): {0}", ex));
             Logger.Error(string.Format("Error in timer ({0})", callerplugin), ex);
         }
     });
     Timer tmr = Timer.Create(delay, numiterations, callback);
     timers.Add(tmr);
     tmr.OnFinished += (t) => timers.Remove(t);
     return tmr;
 }
コード例 #33
0
 public Decision CreateDecision( string desc, LuaFunction func, int cost )
 {
     var d = new Decision( desc, () => { func.Call(); }, cost );
     return d;
 }
コード例 #34
0
ファイル: CodeGeneration.cs プロジェクト: SD-J/UnityLua
		/*
		 * Gets an event handler for the event type that delegates to the eventHandler Lua function.
		 * Caches the generated type.
		 */
		public LuaEventHandler GetEvent (Type eventHandlerType, LuaFunction eventHandler)
		{
			throw new NotImplementedException (" Emit not available on Unity ");
		}
コード例 #35
0
ファイル: Main.cs プロジェクト: ReizeiMako/Oxide
 private bool lua_PostWebRequest(string url, string postdata, LuaFunction func)
 {
     AsyncWebRequest req = new AsyncWebRequest(url, postdata);
     webrequestQueue.Enqueue(req);
     Plugin callerplugin = Plugin.CurrentPlugin;
     req.OnResponse += (r) =>
     {
         try
         {
             func.Call(r.ResponseCode, r.Response);
         }
         catch (Exception ex)
         {
             //Debug.LogError(string.Format("Error in webrequest callback: {0}", ex));
             Logger.Error(string.Format("Error in webrequest callback ({0})", callerplugin), ex);
         }
     };
     return true;
 }
コード例 #36
0
ファイル: CodeGeneration.cs プロジェクト: CartBlanche/NLua
        /*
         * Gets an event handler for the event type that delegates to the eventHandler Lua function.
         * Caches the generated type.
         */
        public LuaEventHandler GetEvent(Type eventHandlerType, LuaFunction eventHandler)
        {
            #if MONOTOUCH
            throw new NotImplementedException (" Emit not available on MonoTouch ");
            #else
            Type eventConsumerType;

            if (eventHandlerCollection.ContainsKey (eventHandlerType))
                eventConsumerType = eventHandlerCollection [eventHandlerType];
            else {
                eventConsumerType = GenerateEvent (eventHandlerType);
                eventHandlerCollection [eventHandlerType] = eventConsumerType;
            }

            var luaEventHandler = (LuaEventHandler)Activator.CreateInstance (eventConsumerType);
            luaEventHandler.handler = eventHandler;
            return luaEventHandler;
            #endif
        }
コード例 #37
0
 public void BindClick(Control control, NLua.LuaFunction function)
 {
     control.MouseClick += Control_MouseClick;
     controlToLua.Add(control, function);
 }