Exemple #1
1
        /// <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;
        }
 public IfElseStatement(LuaFunction checkstate_function)
 {
     conditionCheckFunction = checkstate_function;
     executionBlock = null;
     nextStatement = null;
     executingStatement = null;
 }
Exemple #3
0
 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"];
 }
        protected internal override void AddToActor(CompositeActor actor)
        {
            base.AddToActor(actor);

            string functionName = $"checkTransition{Name}";
            conditionFunction = actor.ScriptSystem.LoadString($"return {condition}", functionName);
        }
Exemple #5
0
 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;
 }
Exemple #6
0
 public static void SetPath(string v_path)
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("setPath");
     if (fun != null)
     {
         fun.Call(v_path);
     }
 }
        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");
        }
 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");
 }
Exemple #9
0
 public static void DoMain()
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("main");
     try
     {
         fun.Call();
     }
     catch (Exception ex)
     {
         Debug.Exception("执行main报错,信息是" + ex.ToString());
     }
 }
    /// <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));
        }
    }
 public static ClientChatLineDelegate MakeDelegate(LuaFunction lua)
 {
     return((int groupId, ref string message, ref EnumHandling handled) => {
         lua.Call(groupId, message, handled);
     });
 }
Exemple #12
0
 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;
 }
 public void RegisterHook(string name, LuaFunction function)
 {
     Console.WriteLine("\t Hook Registered: " + name);
     hooks[name] = function;
 }
Exemple #14
0
 public void Event()
 {
     this.UseItemEvent = Lua.GetFunction("UseItmeTrigGer");
     this.OpenItemEvent = Lua.GetFunction("OpenItmeTrigGer");
     this.MonsterDeadEvent = Lua.GetFunction("DestroyMonster");
 }
Exemple #15
0
        /// <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;
            }
        }
Exemple #16
0
 public CozyLuaFunction(LuaFunction func)
 {
     mFunc = func;
 }
Exemple #17
0
 //延迟执行
 public void LuaInvoke(float delaytime,LuaFunction func,params object[] args)
 {
     StartCoroutine(doInvoke(delaytime, func, args));
 }
Exemple #18
0
 private IEnumerator doCoroutine(YieldInstruction ins, LuaFunction func, params object[] args)
 {
     yield return ins;
     if (args != null)
     {
         func.Call(args);
     }
     else
     {
         func.Call();
     }
 }
Exemple #19
0
 public void on(string eventName, LuaFunction func)
 {
     if (!luaEvents.ContainsKey(eventName))
         luaEvents[eventName.ToLower().Trim()] = new List<LuaFunction>();
     luaEvents[eventName.ToLower().Trim()].Add(func);
 }
Exemple #20
0
        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);
        }
Exemple #21
0
 public LTDescr setOnComplete(LuaFunction onComplete)
 {
     this.onLuaComplete = onComplete;
     return this;
 }
Exemple #22
0
    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);
    }
Exemple #23
0
 public static int delayedCall(float delayTime, LuaFunction callback, object[] optional)
 {
     init();
     return delayedCall(tweenEmpty, delayTime, callback, h(optional));
 }
Exemple #24
0
 public static int delayedCall(float delayTime, LuaFunction callback, Hashtable optional)
 {
     init();
     return delayedCall(tweenEmpty, delayTime, callback, optional);
 }
Exemple #25
0
 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;
     }
 }
Exemple #26
0
        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");
        }
Exemple #27
0
        /*
         * 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");
        }
Exemple #28
0
 //协程
 public void RunCoroutine(YieldInstruction ins, LuaFunction func, params object[] args)
 {
     StartCoroutine(doCoroutine(ins, func, args));
 }
Exemple #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 ");
 }
Exemple #30
0
 private IEnumerator doInvoke(float delaytime, LuaFunction func, params object[] args)
 {
     yield return new  WaitForSeconds(delaytime);
     if (args != null)
     {
         func.Call(args);
     }
     else
     {
         func.Call();
     }
 }
Exemple #31
0
 public static void DoMain()
 {
     Lua.LuaFunction fun = lua_instence.GetFunction("main");
     fun.Call();
 }
Exemple #32
0
 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;
 }
 public Decision CreateDecision( string desc, LuaFunction func, int cost )
 {
     var d = new Decision( desc, () => { func.Call(); }, cost );
     return d;
 }
Exemple #34
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 ");
		}
Exemple #35
0
 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;
 }
Exemple #36
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)
        {
            #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
        }
Exemple #37
0
 public void BindClick(Control control, NLua.LuaFunction function)
 {
     control.MouseClick += Control_MouseClick;
     controlToLua.Add(control, function);
 }